asp.net mvc - If(ModelState.IsValid==false) return View(); or View(model);? -
when validation fails, 1 should return? view(); or view(model); ?
i notice both work. confusing.
edit:
public class moviescontroller : controller {     moviesentities db = new moviesentities();      //     // get: /movies/      public actionresult index()     {         var movies = 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);     } }   my 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 list", "index") %> </div>      
if view returning typed , uses model better pass model. if return view() , in view try access model nullreferenceexception.
the following common pattern:
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");     } }      
Comments
Post a Comment