ASP.NET MVC - prevent双形发帖 [英] ASP.NET MVC - Prevent Double Form Posting

查看:78
本文介绍了ASP.NET MVC - prevent双形发帖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ASP.NET MVC的形式,但需要通过jQuery来发布从它的数据(不AJAX )。它不能使用正常模式提交,因为控制器动作的要求 JSON字符串,并得到该字符串的唯一方式是使用jQuery的$ .post的方法把数据放入JSON,然后其发布到控制器。

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.

如果我用返回false;在我的jQuery code,它会尝试从后再次停止形式,但这并没有解决我的问题。我真的不想手动设置URL,或者说,因为我想保持尽可能多出来的JavaScript以不可思议的。

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.

    [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});
            });

该提交code正确。如果我通过它在调试步骤return语句甚至被击中,但它从来不重定向。我该怎么办?

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.

然后在你的成功回调,通过设置 window.location的使用JavaScript重定向方法。

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

例如。注:这是未经测试,可能无法正常工作的究竟的这个样子,但你的JIST

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

控制器

[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,结果
查尔斯

HTHs,
Charles

这篇关于ASP.NET MVC - prevent双形发帖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆