Monday, July 8, 2013

ASP.NET MVC Views without Model binding

If you converting your existing Classic ASP or ASP.NET WebForms over to ASP.NET MVC Views, you may not be able to use strongly typed views in many cases.  This is especially true if you have a lot of special presentation formatting and logic that you need to preserve from your previous code base.

Fortunately, ASP.NET MVC provides implicit model binding in your views which thereby relieves you of the responsibility of creating all of your ASP.NET MVC Views as strongly typed views.

How does it do that exactly?  Basically, through the use of ViewModels.

If you are not familiar with the concept of a ViewModel, a ViewModel is simply a view of the data that you need in your presentation layer.  The ViewModel acts as a layer of separation between your actual Model (which usually looks nothing like what is required for your presentation view) and your actual View.  A ViewModel essentially represents the object-relational mapping of all of the data that is required for your View in the form of properties on a class.

Therefore, when you create a ViewModel class, you need to explicitly create properties on your class such that they correspond EXACTLY to IDs/names of the fields on your ASP.NET MVC View.  For example, if you have a field called

<input type="text" id="Name" />

Then you will also need a class that has a Name property on it like so:

public class MyViewModel
public string Name {get; set;}

Now, when you want to pass the entire contents of your ASP.NET MVC View back to your Controller method, you can pass it in the form of a single object (rather than handling Request.Form or Request.QueryString operations):

public ActionResult Edit(MyViewModel model)
//perform some operations here
//NOTE: you can directly reference the values from your model here
string name = model.Name;
That is all there is to it!

No comments:

Post a Comment