Enable editing of enumerable data in ASP.NET MVC
I’m currently working on an ASP.NET MVC project. Today I stumbled across a requirement that involved enabling the editing of data that is displayed (on a lets call it master page). The specialty of the data is it’s an enumerable.
I had a few Ideas how to solve the problem.
1. Ajaxification
Pro: I like jQuery. I like that you can directly edit stuff
Con: I like to have a low-level fallback
2. The UeberEditorTemplate.ascx
Pro: On first sight an easy way out
Con: Yakk! all that logic in one editor template.
Both did not really satisfy me. So I started playing around a bit.
The first thing I figured out is that editor templates can be used with c# currying:
Next I created my action that handles the post to inspect the forms collection the templates would create.
This is the time where a custom model binder can be a really be a helpful friend. I switched to a view model that contains the enumerable to enable the model binder through the class attribute:
[ModelBinder(typeof(UserContactDataBinder))]
public class Xyz
{
public List<MyDataItem> Data { get; set; }
}
And finally created the model binder:
public object BindModel(
ControllerContext controllerContext,
ModelBindingContext bindingContext)
{
var model = new Xyz();
model.Data = new List<MYDataItem>();
var context =
controllerContext.HttpContext;
var formValues =
context.Request.Form;
var values =
formValues["data.Value"].Split(',');
for (int i = 0; i < values.Length; i++)
{
var ucd =
new MyDataItem
{
Value = values[i],
};
model.Data.Add(ucd);
}
return model;
}
}
That’s it!
ASP.NET MVC really rocks!