[HttpPost] public ActionResult Create (FormCollection collection) VERSUS [HttpPost] public ActionResult Create (dinner)

In a book by Scott Hanselman (chapter 1), he offers us two implementation options [HttpPost] for creating an action method.

The first of these relies on TryUpdateModel to update the model object based on the input form fields. When the fields in the input form contain invalid input, ModelState.IsValid will be set to false.

[HttpPost] public ActionResult Create(FormCollection collection) { Dinner dinner = new Dinner(); if (TryUpdateModel(dinner)) { dinnerRepository.Add(dinner); dinnerRepository.Save(); return RedirectToAction("Details", new { id = dinner.DinnerId }); } else return View(dinner); } 

The second method is to use the model passed as the arg creation method, as follows:

  [HttpPost] public ActionResult Create(Dinner dinner) { if (ModelState.IsValid) { dinnerRepository.Add(dinner); dinnerRepository.Save(); return RedirectToAction("Details", new { id = dinner.DinnerId }); } else return View(dinner); } 

Which one is recommended for use in production?

+6
asp.net-mvc asp.net-mvc-2
source share
1 answer

If all your required data is either in the request. Forms, route data, or in the query string of the URL, then you can use the model binding, as in your second example.

The model linker creates your dinner object and populates it with data from the request by matching property names.

You can customize the binding process with whitelists, blacklists, prefixes, and marker interfaces. Just make sure you don’t accidentally bind the values ​​- see Link.

+5
source

All Articles