I’m trying to execute my controller from javascript using jquery… here is my jquery code that is executing..
<script type="text/javascript">
$('form').submit(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: $(this).attr("action"),
data: $(this).serialize(),
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function(msg) {
var obj = msg.deserialize();
alert(msg);
}
});
});
</script>
Now it does execute my action..
Here is a sample of my controller class it is executing..
[AcceptVerbs(HttpVerbs.Post)]
[Url("Account/LogOn")]
public virtual ActionResult LogOn(string Username, string Password) {
if (Username == "test") {
return Json(new {
Success = true
});
} else {
return Json(new {
Success = false
});
}
}
Problem is.. when I run the method.. it just tries to download a “Logon” file which contains the result.. how do I put it back to an object in jquery so i can handle it the correct way, I’ve tried adding the success tag and attempt to check the msg but it doesnt even run it
Put your script inside
document.readybefore attempting to register any event handlers as the DOM might have not loaded yet:Also you don’t need to set the
dataType, jQuery knows it from the Content-Type response header from the server. Another remark: the msg object passed to the success handler is already a JSON object: you don’t need to parse/deserialize it:And the solution I would recommend you is to use the jquery.form plugin. Thanks to it your js code will look as easy as:
Very neat stuff. You don’t need to bother about serializing/deserializing data, preventing default events, it can even handle file uploads.