我有以下代码。它的形式简单。如果验证失败,用户输入的内容仍会显示在表单中。这样做怎么样?在控制器中我所做的就是返回一个View(),我不会将模型传递给它。它工作正常,但我需要澄清其工作原理
这是控制器
[HttpGet]
public ViewResult RsvpForm()
{
return View();
}
[HttpPost]
public ViewResult RsvpForm(GuestResponse guestResponse)
{
if (ModelState.IsValid)
{
return View("Thanks", guestResponse);
}
else
{
return View();
}
}
视图是RsvpForm
@model PartyInvites.Models.GuestResponse
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>RsvpForm</title>
</head>
<body>
@using (Html.BeginForm())
{
@Html.ValidationSummary()
<p>Your name: @Html.TextBoxFor(x=>x.Name)</p>
<p>Your email: @Html.TextBoxFor(x=>x.Email)</p>
<p>Your phone: @Html.TextBoxFor(x=>x.Phone)</p>
<p>
Will you attend?
@Html.DropDownListFor(x => x.WillAttend,new[] {
new SelectListItem() { Text = "Yes, I'll be there", Value = bool.TrueString},
new SelectListItem() { Text = "No, I can't come", Value = bool.FalseString}}, "Choose an option")
</p>
<input type="submit" value="Submit RSVP" />
}
</body>
</html>
答案 0 :(得分:1)
ASP.NET MVC假设您在渲染视图以响应 HTTP POST,你正在使用Html助手,那么你很有可能 重新显示验证失败的表单。
您可以在此处详细了解它:http://blogs.msdn.com/b/simonince/archive/2010/05/05/asp-net-mvc-s-html-helpers-render-the-wrong-value.aspx