In Scott Hanselman's book (chapter 1), he provides us with two options to implement [HttpPost] for Create action method.
The first one relies on the TryUpdateModel to update a model object based on the incoming form fields. When the incoming form fields contains invalid input, the 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 utilize a model passed as Create action method arg 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 more recommended to use in production ?
If all your required data is either in Request.Form, route data, or the URL query string, then you can use model binding like in your second example.
The model binder creates your dinner object and populates it with data from the request by matching up property names.
You can customize the binding process with “white lists”, “black lists”, prefixes, and marker interfaces. Just make sure you don't unintentionally bind values – see this link.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With