验证失败时,我应该返回哪一个?视图();或查看(模型); ?
我注意到两者都有效。这很令人困惑。
编辑:
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>
答案 0 :(得分:10)
如果要返回的视图是强类型的并使用模型,那么最好传递此模型。如果您只是return View()
并且在视图中尝试访问该模型,则很可能会获得NullReferenceException
。
以下是一种常见模式:
public class HomeController: Controller
{
public ActionResult Index()
{
var model = FetchModelFromRepo();
return View(model);
}
[HttpPost]
public ActionResult Index(SomeViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// TODO: update db
return RedirectToAction("index");
}
}