2012-07-06 32 views
3

所以我試圖申請Darin Dimitrov's answer,但在我的實現中bindingContext.ModelName等於「」。bindingContext.ModelName是否爲空?

這裏是我的視圖模型:

public class UrunViewModel 
{ 
    public Urun Urun { get; set; } 
    public Type UrunType { get; set; } 
} 

這裏的視圖的一部分職位的模型類型:

@model UrunViewModel 

@{ 
    ViewBag.Title = "Tablo Ekle"; 

    var types = new List<Tuple<string, Type>>(); 
    types.Add(new Tuple<string, Type>("Tuval Baskı", typeof(TuvalBaski))); 
    types.Add(new Tuple<string, Type>("Yağlı Boya", typeof(YagliBoya))); 
} 

<h2>Tablo Ekle</h2> 

    @using (Html.BeginForm("UrunEkle", "Yonetici")) { 
     @Html.ValidationSummary(true) 
     <fieldset> 
      <legend>Tablo</legend> 

      @Html.DropDownListFor(m => m.UrunType, new SelectList(types, "Item2", "Item1")) 

這是我的自定義模型粘合劑:

public class UrunBinder : DefaultModelBinder 
{ 
    protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type type) 
    { 
     var typeValue = bindingContext.ValueProvider.GetValue(bindingContext.ModelName + ".Urun"); 

     var model = Activator.CreateInstance((Type)typeValue.ConvertTo(typeof(Type))); 
      bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, type); 

     return model; 
    } 
} 

最後, Global.asax.cs中的行:

ModelBinders.Binders.Add(typeof(UrunViewModel), new UrunBinder()); 

這裏面重載的CreateModel函數,在調試模式下我可以看到bindingContext.ModelName等於「」。並且,typeValue爲空,所以CreateInstance函數失敗。

回答

1

我不相信你需要bindingContext.ModelName財產爲你想要做的。

經過Darin Dimitrov's answer,它看起來像你可以嘗試以下。首先,你需要的隱藏字段窗體上的類型:

@using (Html.BeginForm("UrunEkle", "Yonetici")) { 
    @Html.Hidden("UrunType", Model.Urun.GetType()) 

然後在你的模型綁定(基本上都是從Darin的季米特洛夫複製):

protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) 
{ 
    var typeValue = bindingContext.ValueProvider.GetValue("UrunType"); 
    var type = Type.GetType(
     (string)typeValue.ConvertTo(typeof(string)), 
     true 
    ); 
    var model = Activator.CreateInstance(type); 
    bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, type); 
    return model; 
} 

有關bindingContext.ModelName是如何的詳細信息,請參閱this post填充。

+0

bindingContext.ValueProvider.GetValue(「UrunType」)確實有效。我無法讓它創建我想要的實例,但這是一個進步。謝謝。 – Halo 2012-07-06 22:49:10

+0

好吧,我設法創建了實例,但是它的派生屬性都是空的。只有基類的屬性被設置 – Halo 2012-07-06 23:11:53