tags:

views:

41

answers:

2

Hi all,

I'm new to asp.net mvc and I came across a project a while back which included an actual Model class as a parameter on an Action Method. It looked something like this:

public ActionResult Index(PersonFormViewModel person)
{
   id = person.Id; ...etc..
}

Can anyone point me to some samples on how to implement something like this within my own project?

Thanks in advance

+1  A: 

It is actually really easy to do, your names on your form elements and your model object just need to line up for the auto binder to work, or you can implement or specify a custom binder. Scott Gu wrote about it on his blog when it first came out in the preview 5 release.

http://weblogs.asp.net/scottgu/archive/2008/10/16/asp-net-mvc-beta-released.aspx

http://weblogs.asp.net/scottgu/archive/2008/09/02/asp-net-mvc-preview-5-and-form-posting-scenarios.aspx

Another nice example:

http://www.bradygaster.com/post/ASPNET-MVC-Model-Binding-Example.aspx

Dean Johnston
+1  A: 

In your view, simply prefix the inputs that correspond to the model's properties with the parameter name of the model. For a model with simple properties this should just work. If your model has complex properties (submodels) you may need to develop a custom model binder. If you have arrays, then you'll need to do some extra formatting in the view side (see Phil Haack's blog on this).

 <%= Html.Hidden("Person.Id") %>
 <%= Html.TextBox("Person.FirstName") %>
 <%= Html.TextBox("Person.LastName" ) %>
tvanfosson