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:

1 [ModelBinder(typeof(UserContactDataBinder))] 2 public class Xyz 3 { 4 public List<MyDataItem> Data { get; set; } 5 }

And finally created the model binder:

1 public object BindModel( 2 ControllerContext controllerContext, 3 ModelBindingContext bindingContext) 4 { 5 var model = new Xyz(); 6 model.Data = new List<MYDataItem>(); 7 var context = 8 controllerContext.HttpContext; 9 var formValues = 10 context.Request.Form; 11 12 var values = 13 formValues["data.Value"].Split(','); 14 15 for (int i = 0; i < values.Length; i++) 16 { 17 var ucd = 18 new MyDataItem 19 { 20 Value = values[i], 21 }; 22 model.Data.Add(ucd); 23 } 24 25 return model; 26 } 27 }

That’s it!

ASP.NET MVC really rocks!

Comments are closed