Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 706
xport Avatar asked Dec 21 '10 06:12

xport


1 Answers

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.

like image 116
kay.herzam Avatar answered Sep 30 '22 15:09

kay.herzam