开发者

MVC Post Json Error

I'm try to issue a post to a MVC action and displaying the resulting JSON on the web page. The action receives the post command but the result is showing up on a new page, instead of the same page. For example, it'll ask if I want to download or open the file. PS. I'm using jQuery validate as well.

my jquer开发者_如何学Goy:

submitHandler: function(form) {
                    $('#loading').show();  //adds waiting spinner
                    $.post(
                        $(form).attr('action'),
                        form.serialize(),
                        function(data) {
                            alert(data);
                        },
                        "json"
                    );
                    return false;
                }

My action:

[AcceptVerbs(HttpVerbs.Post), ValidateAntiForgeryToken]
public ActionResult ContactUs(FormCollection collection) {
    ...
    return Json("OK");
}

I've been banging my head on this and have read way too many web search but still no avail. Any help would be greatly appreciated.


I would recommend you using the jquery form plugin which allows you to do this:

submitHandler: function(form) {
    $('#loading').show();  //adds waiting spinner
    $(form).ajaxSubmit();
}

You can also pass options to the ajaxSubmit method:

$(form).ajaxSubmit({
    success: function(data) {
        alert(data);
    }
});

If you don't want to use any other plugins make sure you do this (notice that the form is wrapped in $() in order to call the serialize method):

$.post(
    form.action,
    $(form).serialize(),
    function(data) {
        alert(data);
    },
    'json'
);


you can test this in action

[AcceptVerbs(HttpVerbs.Post), ValidateAntiForgeryToken]
public ActionResult ContactUs(FormCollection collection) {
...
return new JsonResult() { data = "OK"};
}


Just like @Akyegane solution, but I would do this

[AcceptVerbs(HttpVerbs.Post), ValidateAntiForgeryToken]
public ActionResult ContactUs(FormCollection collection) {
    return Json({ data = "OK"});
}


Thanks, I was browsing the JQuery validate site and it says to try something like this:

            submitHandler: function(form) {
                $(form).ajaxSubmit();
        }

I did and it sort of works. The form submits correctly, but I get this error in FireBug:

$(form).ajaxSubmit is not a function

I've googled a bunch of sites and there's no solution. Should I use jquery form plugin instead of jquery validate? I'm using the latest jquery and Jquery validate CDN packages via:

http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js
http://ajax.microsoft.com/ajax/jQuery.Validate/1.7/jQuery.Validate.min.js
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜