开发者

ASP.NET MVC - Prevent Double Form Posting

开发者 https://www.devze.com 2023-01-22 06:16 出处:网络
I have an ASP.NET MVC Form, but the data from it needs to be posted via jQuery (not ajax). It cannot be submitted using the normal model, because the Controller Action requires a JSON string, and the

I have an ASP.NET MVC Form, but the data from it needs to be posted via jQuery (not ajax). It cannot be submitted using the normal model, because the Controller Action requires a JSON string, and the only way to get that string is to use jQuery's $.post method to turn the data into JSON, and then post it to the Controller.

This works fine. However the end result is that after posting, the form is supposed to Redirect to a different page (Like a Success Page). This does not occur, it just stays on the same page.

If I use return false; in my jQuery code, it will stop the form from trying to post again, but this doesn't solve my problem. I really don't want to set the URL manually, either, since I want to keep as much out of javascript as humanly possible.

Controller

    [HttpPost]
    public ActionResult Receive([FromJson] jsonObject item)
    {
        if (ModelState.IsValid)
        {
                       // logic
        }
        return RedirectToAction( ... );
    }

JavaScript

            $('.submit').click(function(e) {
                    var json = JSON.stringify(data);
                    $.post( location.href, { item: data});
            });
开发者_Go百科

This submits the code right. and the return statement even gets hit if I step through it in the debugger, but it never does the redirect. What can I do?


How about returning a string from your action that is the location you want to redirect to.

Then in your success callback, use the javascript redirect method by setting window.location.

E.g. NOTE: this is untested and probably doesn't work exactly like this, but you get the jist.

Controller

[HttpPost]
public ActionResult Receive([FromJson] jsonObject item)
{
    if (ModelState.IsValid)
    {
                   // logic
    }
    return Json("urltoredirectto");
}

JavaScript

$('.submit').click(function(e) {
    var json = JSON.stringify(data);
    $.post(location.href, { item: data },
        function (data) {
            window.location = data;
        });
});

HTHs,
Charles


Well, $.post is an ajax command so the result it receives is the redirect request. This means the browser won't receive the request because the ajax command is consuming it.

I found this that might help: Use jQuery to attach JSON to a form and submit it

0

精彩评论

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