您需要使用 Post Redirect Get PRG 模式。
请阅读Kazi Manzur Rashid的这篇博文中的使用 PRG 模式进行数据修改部分。http://weblogs.asp.net/rashid/archive/2009/04/01/asp-net-mvc-best-practices-part-1.aspx
此方法用于TempData
维护ModelState
重定向之间的数据。
[HttpPost, ValidateAntiForgeryToken, ExportModelStateToTempData]
public ActionResult Create(FormCollection form)
{
Product p = new Product();
if (TryUpdateModel<IProductModel>(p))
{
productRepository.CreateProduct( p );
}
else
{
// add additional validation messages as needed
ModelState.AddModelError("_generic", "Error Msg");
}
return RedirectToAction("Index");
}
这是你的Index
行动方法。
[ImportModelStateFromTempData]
public ActionResult Index()
{
IList<Product> products = productRepository.GetAll();
return View("Index", products);
}
这是你的Index
观点。
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IList<Product>>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Index
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>Products</h2>
<% foreach (var p in Model) { %>
<div><%= Html.Encode( p.ProductName ) %></div>
<% } %>
<%= Html.ValidationSummary("Please correct the errors", new { id = "valSumCreateForm" }) %>
<% using (Html.BeginForm("Create", "Product")) { %>
Product Name: <%= Html.TextBox("ProductName") %>
<%= Html.AntiForgeryToken() %>
<% ViewContext.FormContext.ValidationSummaryId = "valSumCreateForm"; %>
<% } %>
</asp:Content>
ImportModelStateFromTempData
andExportModelStateToTempData
属性有助于在重定向之间传输模型状态错误。这
<% ViewContext.FormContext.ValidationSummaryId = "valSumCreateForm"; %>
将 MVC 表单与其相应的验证摘要相关联。
你也可以在这里查看我的另一个答案。
在 ASP.NET MVC2 中具有 SelectList 绑定的 ViewModel
如果您有任何问题,请告诉我。
-苏