ASP.NET MVC - 提交表单后刷新页面

时间:2017-04-10 20:35:56

标签: asp.net-mvc-4

我目前的要求是在首次提交表单后向用户显示警告消息。当用户下次单击提交按钮时,应该保存它,因为用户可以忽略警告消息。

我使用会话变量显示警告消息,并将计数设置为“1”以显示警告消息。

问题是当用户刷新页面时,表单将在视图模型传递给操作时提交。我不希望刷新提交表单。

由于第一次会话变量为1,因此刷新也会提取与提交操作相同的视图模型。

如果有办法区分MVC中的刷新和提交操作,请提供帮助。

1 个答案:

答案 0 :(得分:0)

这实际上取决于警告的内容,是警告检查某些内容还是默认警告始终存在?

如果默认情况下它始终存在,最简单的解决方案是在第一次按下虚假提交按钮并启用实际提交按钮时通过某些jquery显示警告,并在警告出现时显示假按钮消失。所以在html的页面上隐藏并禁用提交按钮,最初显示:none和禁用,并在同一个地方放置一个假按钮,然后在js中显示如下内容:

$('#yourformidhere').submit(function () {
            $('#fakesubmitbutton').hide();
            $('#realsubmitbutton'.show();
            $(this).find(':submit').prop('disabled', 'false');
        });

如果你必须检查服务器端,那么你需要通过控制器返回页面和模型。在页面上使用隐藏的标记设置为“1”,然后在控制器中执行检查并返回页面,如果检查失败,模型字段的标记变为“2”以及警告。然后,用户可以再次提交表单,您的控制器操作会检查“2”,如果发现它允许在没有检查的情况下提交表单。

编辑 - 示例:

表格:

@using (Html.BeginForm()){

@Html.Hiddenfor(model => model.hidden)

@Html.EditorFor(model = model.data1)

<input type ="submit" value"submit"/>
}

视图模型:

public class someviewmodel{

public string data1 { get; set; }
public int hidden { get; set; }

}

控制器

public ActionResult forumsubmit(someviewmodel model)
        {

//check to see if this is the first submission attempt

if (model.hidden == null){

      //check for whatever you need regarding the warning e.g.

      if (model.data1 == needswarning){

      //add your warning message here if it is to appear on the page for example a viewbag
      ViewBag.warning = "you've been warned"

     //change hidden field to 1 to acknowledge first submission attempt
     model.hidden = 1;

     //returns view with information intact for second submission
     return View(model);
    }

}

//if you reach here in the controller action the hidden field is either not null or there is no need for a warning so you can now process the form and add info to db here.

return View("submitsuccess")

}