Question on ASP.NET MVC NerdDinner

I am following the Scott Guthries MVC study guide ( http://nerddinnerbook.s3.amazonaws.com/Part6.htm ), and there is something I don’t understand.

The Controller class called DinnersController has the following Create methods:

public ActionResult Create() { Dinner dinner = new Dinner() { EventDate = DateTime.Now.AddDays(7) }; return View(new DinnerFormViewModel(dinner)); } [AcceptVerbs( HttpVerbs.Post)] public ActionResult Create(Dinner dinner) { if (ModelState.IsValid) { try { dinner.HostedBy = "SomeUser"; dinnerRepository.Add(dinner); dinnerRepository.Save(); return RedirectToAction("Details", new { id = dinner.DinnerID }); } catch { foreach (var violation in dinner.GetRuleViolations()) ModelState.AddModelError(violation.PropertyName, violation.ErrorMessage); } } return View(new DinnerFormViewModel(dinner)); } 

The first method calls the display of the Create.aspx page, which displays the form data for the object type "DinnerViewFormModel" ie

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<NerdDinner.Controllers.DinnerFormViewModel>" %>

The "DinnerViewFormModel" class contains the "Dinner" property, therefore, displaying the corresponding information for objects of the "Dinner" type is done by calling:

<label for="Title">Title:</label> <%= Html.TextBox("Title", Model.Dinner.Title) %>

I understand what is happening so far. However, Create.aspx does contain a submit type button:

<input type="submit" value="Create" />

When a button is pressed, the following method is called:

  [AcceptVerbs( HttpVerbs.Post)] public ActionResult Create(Dinner dinner) 

I don’t understand if the model data form is a DinnerViewFormModel object, how does MVC know that the “Dinner” object needs to be passed to the Create method?

Please can someone enlighten me? Thanks

+4
source share
2 answers

AFAIK, MVC is simply trying to display the properties available in POST to the parameter that it provided. Because of this, he does not need to know about the type, he simply creates an object with a standard constructor and displays the form values ​​for the created object - and this is what you get as the value of the method parameter.

BTW: You will also notice that the output of the view does not reference the Dinner or DinnerFormViewModel .

+3
source

It is called "model binding" and is built into ASP.NET MVC. Your action methods need data, and an incoming HTTP request contains the data you need. The trick is that the data is embedded in the POST-ed values ​​of the form, and possibly the URL itself. Enter DefaultModelBinder, which can magically transform form values ​​and route data to objects. Interaction with the model allows your controller to remain cleanly separated from the dirtiness of the request request and its associated environment.

+4
source

All Articles