MVC ajax post to controller action method
It's due to you sending one object, and you're expecting two parameters.
Try this and you'll see:
public class UserDetails
{
public string username { get; set; }
public string password { get; set; }
}
public JsonResult Login(UserDetails data)
{
string error = "";
//the rest of your code
}
Your Action is expecting string parameters, but you're sending a composite object.
You need to create an object that matches what you're sending.
public class Data
{
public string username { get;set; }
public string password { get;set; }
}
public JsonResult Login(Data data)
{
}
EDIT
In addition, toStringify() is probably not what you want here. Just send the object itself.
data: data,
try this:
/////// Controller post and get simple text value
[HttpPost]
public string Contact(string message)
{
return "<h1>Hi,</h1>we got your message, <br />" + message + " <br />Thanks a lot";
}
//// in the view add reference to the Javascript (jQuery) files
@section Scripts{
<script src="~/Scripts/modernizr-2.6.2.js"></script>
<script src="~/Scripts/jquery-1.8.2.intellisense.js"></script>
<script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
}
/// then add the Post method as following:
<script type="text/javascript">
/// post and get text value
$("#send").on("click", function () {
$.post('', { message: $('#msg').val() })
//// empty post('') means post to the default controller,
///we are not pacifying different action or controller
/// however we can define a url as following:
/// var url = "@(Url.Action("GetDataAction", "GetDataController"))"
.done(function (response) {
$("#myform").html(response);
})
.error(function () { alert('Error') })
.success(function () { alert('OK') })
return false;
});
Now let's say you want to do it using $.Ajax and JSON:
// Post JSON data add using System.Net;
[HttpPost]
public JsonResult JsonFullName(string fname, string lastname)
{
var data = "{ \"fname\" : \"" + fname + " \" , \"lastname\" : \"" + lastname + "\" }";
//// you have to add the JsonRequestBehavior.AllowGet
//// otherwise it will throw an exception on run-time.
return Json(data, JsonRequestBehavior.AllowGet);
}
Then, inside your view: add the event click on a an input of type button, or even a from submit: Just make sure your JSON data is well formatted.
$("#jsonGetfullname").on("click", function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "@(Url.Action("JsonFullName", "Home"))",
data: "{ \"fname\" : \"Mahmoud\" , \"lastname\" : \"Sayed\" }",
dataType: "json",
success: function (data) {
var res = $.parseJSON(data);
$("#myform").html("<h3>Json data: <h3>" + res.fname + ", " + res.lastname)
},
error: function (xhr, err) {
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
}
})
});