2010-09-27 129 views
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> 

回答

9

如果要返回視圖是強類型和使用模型倒不如通過這種模式。如果您只是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"); 
    } 
} 
+0

我的看法是強類型。在幕後,爲什麼兩個人都能給我同樣的結果?我很困惑。 – xport 2010-09-27 11:21:08

+1

也許是因爲在您的視圖中,您只使用Html助手,默認情況下會首先查看POST請求,然後查看綁定其值時的模型。但是,如果您嘗試手動訪問模型的屬性(如<%:Model.FooProp%>),它可能會引發異常。所以如果你有一個強類型視圖**總是**傳遞模型。 – 2010-09-27 11:22:58

+0

由VWD生成的腳手架中的Html助手不是強類型的? – xport 2010-09-27 11:31:04

相關問題