该约定已经可用,而无需跳过太多圈子。诀窍是根据您传递给视图的模型连接 TextBox 值。
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult CreatePost()
{
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult CreatePost(FormCollection formCollection)
{
try
{
// do your logic here
// maybe u want to stop and return the form
return View(formCollection);
}
catch
{
// this will pass the collection back to the ViewEngine
return View(formCollection);
}
}
接下来发生的是 ViewEngine 采用 formCollection 并使用 Html 帮助程序将集合中的键与您在视图中拥有的 ID 名称/值进行匹配。例如:
<div id="content">
<% using (Html.BeginForm()) { %>
Enter the Post Title: <%= Html.TextBox("Title", Model["Title"], 50) %><br />
Enter the Post Body: <%= Html.TextArea("Body", Model["Body"]) %><br />
<%= Html.SubmitButton() %>
<% } %>
</div>
注意 textbox 和 textarea 有 Title 和 Body 的 ID?现在,请注意我是如何从 View 的 Model 对象中设置值的?由于您传入了 FormCollection(并且您应该使用 FormCollection 将视图设置为强类型),您现在可以访问它。或者,没有强类型,你可以简单地使用 ViewData["Title"] (我认为)。
POOF你神奇的 ViewState。这个概念称为约定优于配置。
现在,上面的代码是使用 FormCollection 的最简单、最原始的形式。当您开始使用 ViewModels 而不是 FormCollection 时,事情会变得有趣。您可以开始添加自己的模型/视图模型验证,并让控制器自动冒泡自定义验证错误。不过,这是另一天的答案。
我会建议使用 PostFormViewModel 而不是 Post 对象,但要每个人自己。无论哪种方式,通过在 action 方法上需要一个对象,您现在可以获得一个可以调用的 IsValid() 方法。
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult CreatePost(Post post)
{
// errors should already be in the collection here
if (false == ModelState.IsValid())
return View(post);
try
{
// do your logic here
// maybe u want to stop and return the form
return View(post);
}
catch
{
// this will pass the collection back to the ViewEngine
return View(post);
}
}
你的强类型视图需要调整:
<div id="content">
<% using (Html.BeginForm()) { %>
Enter the Post Title: <%= Html.TextBox("Title", Model.Title, 50) %><br />
Enter the Post Body: <%= Html.TextArea("Body", Model.Body) %><br />
<%= Html.SubmitButton() %>
<% } %>
</div>
您可以更进一步,并直接从您在控制器中设置的 ModelState 在视图中显示错误。
<div id="content">
<%= Html.ValidationSummary() %>
<% using (Html.BeginForm()) { %>
Enter the Post Title:
<%= Html.TextBox("Title", Model.Title, 50) %>
<%= Html.ValidationMessage("Title") %><br />
Enter the Post Body:
<%= Html.TextArea("Body", Model.Body) %>
<%= Html.ValidationMessage("Body") %><br />
<%= Html.SubmitButton() %>
<% } %>
</div>
这种方法的有趣之处在于,您会注意到我没有设置验证摘要,也没有设置视图中的单个验证消息。我喜欢练习 DDD 概念,这意味着我的验证消息(和摘要)在我的域中进行控制,并以集合的形式传递。然后,我遍历集合(如果存在任何错误)并将它们添加到当前的 ModelState.AddErrors 集合中。当您返回 View(post) 时,其余部分是自动的。
很多很多的约定都出来了。我强烈推荐的几本书更详细地介绍了这些模式:
按照这个顺序,第一个涵盖了整个 MVC 框架的基本细节。后者涵盖了 Microsoft 官方领域之外的高级技术,以及一些使您的生活更轻松的外部工具(Castle Windsor、Moq 等)。