Given the following types
public class SomeValue
{
public int Id { get; set; }
public int Value { get; set; }
}
public class SomeModel
{
public string SomeProp1 { get; set; }
public string SomeProp2 { get; set; }
public IEnumerable<SomeValue> MyData { get; set; }
}
I want to create an edit form for the type SomeModel
which would contain the usual text fields for SomeProp1
and SomeProp2
and then a table containing a text field for each SomeValue
in the SomeModel.MyData
collection.
How is this done? How do the values get bound back to the model?
I currently have a form displaying a text field for each value but they all have the same name and same Id. This is obviously not valid HTML and will prevent MVC from mapping the values back.
IList
implements IEnumerable so you could modify your model like so:You can use the
IModelBinder
interface to create a binder for your specific model. There are a couple ways to do it. You can create anEditorFor
cshtml for the model which will loop through yourSomeValue
list and output appropriate ids and what not. Then, in yourModelBinder
implementation your would then read through your ids and bind them appropriately. I can post a working sample in a while.You would do it using Editor Templates. This way the framework will take care of everything (from properly naming the input fields to properly binding the values back in the post action).
Controller:
View (
~/Views/Home/Index.aspx
):And finally the Editor Template (
~/Views/Home/EditorTemplates/SomeValue.ascx
) which will be automatically invoked for each element of theMyData
collection: