With ASP.NET MVC the developer has now full control about the HTML rendering and how the form data will be transmitted to the server. But how can you get the form values on the server side? There are better ways in MVC to do that than Request.Form["..."].
Intro
If you are new to ASP.NET MVC, I recommend you to read this post or look at asp.net/mvc.
"Bindings"
In this HowTo you can learn how to access the form data in a more elegant way than Request.Form["..."].
Structure
We have a "BindingController" and in the Model folder a "Person" class and 3 views:
- "CreatePerson" (form to create a person)
- "Result" of the action
- "Index" is the overview page
Person Class:
- public class Person
- {
- public Guid Id { get; set; } </span>
- public string Prename { get; set; } </span>
- public string Surname { get; set; } </span>
- public int Age { get; set; } </span>
- }
Form in CreatePerson.aspx:
- <% using (Html.BeginForm()) { %>
- <fieldset>
- <legend>Fields</legend>
- <p>
- <label for="Id">Id:</label> </span>
- <%= Html.TextBox("Id") %> </span>
- <%= Html.ValidationMessage("Id", "*") %> </span>
- </p>
- <p>
- <label for="Prename">Prename:</label> </span>
- <%= Html.TextBox("Prename") %> </span>
- <%= Html.ValidationMessage("Prename", "*") %> </span>
- </p>
- <p>
- <label for="Surname">Surname:</label> </span>
- <%= Html.TextBox("Surname") %> </span>
- <%= Html.ValidationMessage("Surname", "*") %> </span>
- </p>
- <p>
- <label for="Age">Age:</label> </span>
- <%= Html.TextBox("Age") %> </span>
- <%= Html.ValidationMessage("Age", "*") %> </span>
- </p>
- <p>
- <input type="submit" value="Create" /> </span>
- </p>
- </fieldset>
- <% } %>
Binding: 1. Option - FormCollection:
- [AcceptVerbs(HttpVerbs.Post)]
- public ActionResult FormCollection(FormCollection collection) </span>
- {
- Person person = new Person(); </span>
- person.Prename = collection["Prename"]; </span>
- person.Surname = collection["Surname"]; </span>
- person.Age = int.Parse(collection["Age"]); </span>
- return View("Result", person); </span>
- }
This option is the simplest possible way to access the form data, but not very elegant and hard to test, because you need to know which keys are in the FormCollection.
Binding: 2. Option- Parameter Matching:
- [AcceptVerbs(HttpVerbs.Post)]
- public ActionResult ParameterMatching(string Prename, string Surname, int Age) </span>
- {
- Person person = new Person(); </span>
- person.Prename = Prename;
- person.Surname = Surname;
- person.Age = Age;
- return View("Result", person); </span>
- }
This option is very handy. The HTTP form values will be mapped to the parameters if the type and name are the same as the transmitted form value. This option is easy to test, but you have to map the parameters to your model manually.
Binding: 3. Option - Default Binding:
- [AcceptVerbs(HttpVerbs.Post)]
- public ActionResult DefaultBinding(Person person) </span>
- {
- return View("Result", person); </span>
- }
Now we use our own model as parameter type. The default model binder, which is included in the ASP.NET MVC, will map the incomming HTTP form values to the properties of our person, if type and name match.
Binding: 3. Option with addon - Default Binding with Include:
- [AcceptVerbs(HttpVerbs.Post)]
- public ActionResult DefaultBindingWithInclude([Bind(Include="Prename")] Person person) </span>
- {
- return View("Result", person); </span>
- }
You should think bevor you bind - to secure your applicaiton you can specify which properties will be mapped to the properties of the parameters.
Binding: 3. Option with addon - Default Binding with Exclude:
- [AcceptVerbs(HttpVerbs.Post)]
- public ActionResult DefaultBindingWithExclude([Bind(Exclude = "Prename")] Person person) </span>
- {
- return View("Result", person); </span>
- }
The same functionality, but this time reversed.
Binding: 3. Option with addon - Default Binding with Prefix:
If you put a prefix in your Html Input controls (because you have multiple "name" fields), than you can specify a prefix.
All these options can be used together and you can map more than one parameter.
Binding: 4. Option - IModelBinder
If the values are getting more complex or you want your own mapping logic than you can use the IModelBinder interface. One example is Fileupload or to get the session user.
Now you just need to implement the IModelBinder interface:
- public class PersonModelBinder : IModelBinder
- {
- public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) </span>
- {
- if (controllerContext == null) { </span>
- throw new ArgumentNullException("controllerContext"); </span>
- }
- if (bindingContext == null) { </span>
- throw new ArgumentNullException("bindingContext"); </span>
- }
- NameValueCollection collection = controllerContext.RequestContext.HttpContext.Request.Form;
- Person returnValue = new Person(); </span>
- returnValue.Id = Guid.NewGuid();
- returnValue.Prename = "Modelbinder: " + collection["Prename"]; </span>
- returnValue.Surname = "Modelbinder: " + collection["Surname"]; </span>
- int age = 0; </span>
- int.TryParse(collection["Age"], out age); </span>
- returnValue.Age = age;
- return returnValue; </span>
- }
- }
You get full access to the form values or other controller properties or route value.
You can register your Modelbinder global in the Global.ascx:
- protected void Application_Start()
- {
- RegisterRoutes(RouteTable.Routes);
- ModelBinders.Binders[typeof(Person)] = new PersonModelBinder(); // Important! </span>
- }
Everytime you have a parameter of type "Person" the "PersonModelBinder" will try to map the values to this object.
Or you can specify it per ActionMethod:
- [AcceptVerbs(HttpVerbs.Post)]
- public ActionResult PersonModelBinder([ModelBinder(typeof(PersonModelBinder))] Person person) </span>
- {
- return View("Result", person); </span>
- }
Lists/Array Binding:
You can even "bind" arrays / lists. Read Scott Hanselmans post for more information.
Screens: