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