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
函數失敗。
bindingContext.ValueProvider.GetValue(「UrunType」)確實有效。我無法讓它創建我想要的實例,但這是一個進步。謝謝。 – Halo 2012-07-06 22:49:10
好吧,我設法創建了實例,但是它的派生屬性都是空的。只有基類的屬性被設置 – Halo 2012-07-06 23:11:53