I have a problem with passing values from model to controller, let’s say i have two classes:
public class Model
{
public string Name { get; set; }
public SubClass Value { get; set; }
}
public class SubClass
{
public string Value1 { get; set; }
public string Value2 { get; set; }
}
in view, I’m assigning values to Model’s property value of type SubClass like this :
<%: Html.TextBoxFor(model => model.Value.Value1) %>
<%: Html.TextBoxFor(model => model.Value.Value1) %>
The view is passing to controller only the Name property of Model, the Value property always stays null. Any suggestions ?
This is because by default, the MVC model binder won’t pass (complex i.e. non-primitive types) sub-types back to the controller on a post. Your property
public SubClass Value { get; set; }is a complex type (a class you’ve written called SubClass).You need to write a custom model binder for this, to tell MVC how to post sub-class(es) back with your model. Here’s some great articles on custom model binding to help you get to where you need to be.
http://odetocode.com/Blogs/scott/archive/2009/04/27/12788.aspx
http://odetocode.com/Blogs/scott/archive/2009/05/05/12801.aspx