Dmy*_*tro 4 c# asp.net-mvc modelstate
我有一个家庭控制器
public class HomeController : Controller
{
public ActionResult Index()
{
var m = new ModelClass
{
Prop1 = 1,
Prop2 = "property 2"
};
return View(m);
}
public ActionResult SubAction()
{
ModelState.AddModelError("key", "error message value");
return RedirectToAction("Index");
}
}
Run Code Online (Sandbox Code Playgroud)
模型:
public class ModelClass
{
public int Prop1 { get; set; }
public string Prop2 { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
并查看:
@model MvcApplication9.Models.ModelClass
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@Html.TextBoxFor(m => m.Prop1)
@Html.TextBoxFor(m => m.Prop2)
@Html.ValidationMessage("key")
<br/>
@Html.ActionLink("action", "SubAction", "Home")
Run Code Online (Sandbox Code Playgroud)
当我点击actionactionlink时我希望看到,error message value但是当我重定向SubAction到Index动作时,ModelState错误就会丢失.如何SubAction通过Index操作返回保存那些模型错误,设置并在视图中显示它们?
如果您只是想尝试收到错误消息,请使用TempData:
TempData.Add("error", "I'm all out of bubblegum...");
Run Code Online (Sandbox Code Playgroud)
然后,在您的其他操作或视图中,您可以使用TryGetValue:
object message = string.Empty;
if(TempData.TryGetValue("error", out message)
{
// do something with the message...
}
Run Code Online (Sandbox Code Playgroud)