2011-09-08 33 views
1

鑑於以下派生類型:列表<BaseType>模型綁定

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;} 
} 

我想使用自定義的模型綁定綁定是這樣的:

[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"); 
} 

我的計劃是,每個項目將有一個自定義類型描述符:

<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" /> 

我開發了一個自定義模型箱明鏡針對單個(非集合)對象:

public class EntityTypeModelBinder : DefaultModelBinder 
    { 
     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; 
     } 
    } 

但有人對我怎麼可以轉換這個模型的粘合劑來處理收集什麼建議嗎?我很茫然。

最好的問候和感謝您的答覆。

Hal

回答

1

您顯示的此模型聯編程序已處理集合。所有你需要的是把下面的行放在Application_Start

ModelBinders.Binders.Add(typeof(Base), new EntityTypeModelBinder()); 

它有足夠的智能,它會隨着收藏品的工作,以及因爲沒有註冊的模型粘結劑List<Base>這將是默認的模型綁定即會被調用。它檢測到您擁有一個集合併爲集合的每個元素調用相應的模型聯編程序。而且由於您註冊了Base類型的模型聯編程序,您將自動使用自定義聯編程序。