views:

80

answers:

2

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

+2  A: 

Put your script inside document.ready before attempting to register any event handlers as the DOM might have not loaded yet:

<script type="text/javascript">
    $(function() {
        // ... copy - paste your script here
    });
</script>

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:

<script type="text/javascript">
$(function() {
    $('form').submit(function() {
        $.ajax({
            type: 'POST',
            url: $(this).attr('action'),
            data: $(this).serialize(),
            success: function(msg) {
                alert(msg.Success);
            }
        });
        return false;
    }
});
</script>

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:

<script type="text/javascript">
$(function() {
    $('form').ajaxForm(function(msg) {
        alert(msg.Success);
    });
});
</script>

Very neat stuff. You don't need to bother about serializing/deserializing data, preventing default events, it can even handle file uploads.

Darin Dimitrov
I don't think that it's a bad thing to specify dataType, even though in this specific case JQuery may be able to infer the desired type from the Content-Type header. At one point I was struggling to get an ajax call to a JSON web service working, and the response didn't seem to be deserialized properly unless I specified dataType, even though I had also specified Content-Type as "application/json". Granted, there may have been problems with my web service at the time, though I think dataType is used for a bit more, such as setting the Accept header in the request.
Dr. Wily's Apprentice
@Darin sorry my comment doesn't relates to this question... Though i want to ask you... Have you used Fluent nhibernate with asp.net mvc? If so, suggest a tutorial which would be a good start?
Pandiya Chendur
Just to clarify, the actual problem here AFAIK (which was solved by adding the jQuery bindings after document loaded) is that the form was submitting normally. This redirected the browser to the url that returned the JSON result and then the browser decided it should handle it by downloading as a file.
Owen
A: 

HIDDENHANCEMENT

var obj = msg.deserialize();

If that is not a joke, you would have spotted a hidden feature :)

If you're using jQuery v.1.4.x you don't need to parse a JSON string manually. Using an older version, try

var obj = window.JSON.parse(msg);
jAndy
heh was actually just guessing "deserialize"
LeeHull