Given the following derived types:
public class Base {
public string Id {get;set;}
}
public class Contact : Base {
public string FirstName {get;set;}
public string LastName {get;set;
}
public class Organization : Base {
public string Name {get;set;}
}
I would like to bind something like this using a custom model binder:
[HttpPost]
public ActionResult UpdateMultiple(List<Base> items) {
for each (var item in items) {
if (item.GetType().Equals(typeof(Contact)) {
// update
} else if (item.GetType().Equals(typeof(Organization)) {
// update
}
}
return RedirectToAction("index");
}
My plan is that each item will have a custom type descriptor:
<input type="hidden" name="items[0].EntityType" value="MyNamespace.Contact, MyNamespace, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
<input type="text" name="items[0].FirstName" />
<input type="text" name="items[0].LastName" />
<input type="hidden" name="items[1].EntityType" value="MyNamespace.Organization, MyNamespace, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
<input type="text" name="items[1].Name" />
I've developed a custom model binder for a single (non-collection) object:
public class EntityTypeModelBinder : DefaultModelBinde开发者_如何转开发r
{
protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
{
var typeValue = bindingContext.ValueProvider.GetValue(bindingContext.ModelName + ".EntityType");
var type = Type.GetType((string)typeValue.ConvertTo(typeof(string)),true);
var model = Activator.CreateInstance(type);
bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, type);
return model;
}
}
But does anyone have any suggestions on how I could convert this model binder to handle a collection? I'm at a loss.
Best regards and thanks for the response.
Hal
This model binder you have shown already handles collections. All you need is to put the following line in your Application_Start
:
ModelBinders.Binders.Add(typeof(Base), new EntityTypeModelBinder());
It is intelligent enough and it will work with collections as well because there is not registered model binder for List<Base>
it will be the default model binder that will be invoked. It detects that you have a collection and invokes the corresponding model binder for each element of the collection. And because you have registered a model binder for the Base
type you custom binder will be automatically used.
精彩评论