10
当验证失败时,我应该返回哪一个?视图();或查看(模型); ?If(ModelState.IsValid == false)return View();或查看(模型);?
我注意到这两个工作。这很混乱。
编辑:
public class MoviesController : Controller
{
MoviesEntities db = new MoviesEntities();
//
// GET: /Movies/
public ActionResult Index()
{
var movies = from m in db.Movies
select m;
return View(movies.ToList());
}
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(Movie movie)
{
if (ModelState.IsValid)
{
db.AddToMovies(movie);
db.SaveChanges();
return RedirectToAction("Index");
}
else
return View();//View(movie);
}
}
我Create.aspx:
<% using (Html.BeginForm()) {%>
<%: Html.ValidationSummary(true) %>
<fieldset>
<legend>Fields</legend>
<div class="editor-label">
<%: Html.LabelFor(model => model.Title) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.Title) %>
<%: Html.ValidationMessageFor(model => model.Title) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.ReleaseDate) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.ReleaseDate) %>
<%: Html.ValidationMessageFor(model => model.ReleaseDate) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.Genre) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.Genre) %>
<%: Html.ValidationMessageFor(model => model.Genre) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.Price) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.Price) %>
<%: Html.ValidationMessageFor(model => model.Price) %>
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
<% } %>
<div>
<%: Html.ActionLink("Back to List", "Index") %>
</div>
我的看法是强类型。在幕后,为什么两个人都能给我同样的结果?我很困惑。 – xport 2010-09-27 11:21:08
也许是因为在您的视图中,您只使用Html助手,默认情况下会首先查看POST请求,然后查看绑定其值时的模型。但是,如果您尝试手动访问模型的属性(如<%:Model.FooProp%>),它可能会引发异常。所以如果你有一个强类型视图**总是**传递模型。 – 2010-09-27 11:22:58
由VWD生成的脚手架中的Html助手不是强类型的? – xport 2010-09-27 11:31:04