Binding in ASP.NET MVC
Date Published: 10 June 2009
At my ASP.NET MVC + SOLID Principles talk in Cleveland last night, I had a couple of questions about binding in ASP.NET MVC. For instance:
- Can you still do something like <%= Bind(“Foo”) %> in your form?
- How does the controller that receives a POST get back the Model that was used in the form that was posted?
- Does it have to be serializable?
- What if I need to bind custom types to my Model class?
- Doesn’t having the Model referenced in the View eliminate the need for the Controller?
I answered these last night but I thought they were common enough as a theme that they deserved their own answers here as well.
Does ASP.NET MVC Support Two Way Binding via the Bind() Syntax?
No, not directly. Rather, you can use HTML Helpers to create your UI (if you like – you can also just hand code the HTML if that’s your preference – ASP.NET MVC is all about you being in control), and then use either the built-in or a custom ModelBinder to convert the POSTed data into your class/Model. More on ModelBinders below. The HTML helper syntax might look like this:
<%= Html.TextBox(<span style="color: #006080">"Title"</span>, Model.Title) %>
If you don’t like the “magic string” used in this, you might look at Eric Hexter’s Input Builders project.
How does the controller that handles the POST get back the Model?
In my example last night, I had some code that looked like this (except it used a blog not a customer):
[AcceptVerbs(HttpVerbs.Post)]
<span style="color: #0000ff">public</span> ActionResult Create(Customer customer)
{
<span style="color: #008000">// work with Customer here</span>
}
This kind of looks like it’s using Magic, because nowhere am I having to deal with Request.Form[“CustomerName”] or CustomerTextBox.CustomerName as I would typically need to do. It raises the question for some as to whether there is some kind of passing around of the serialized model (Customer) between the client and the server. In fact this is not the case. All that is happening here is standard HTTP, doing a POST, with the fields that were specified in the
Tags - Browse all tags
Category - Browse all categories
About Ardalis
Software Architect
Steve is an experienced software architect and trainer, focusing on code quality and Domain-Driven Design with .NET.