Hal*_*alo 7 c# defaultmodelbinder asp.net-mvc-3
所以我试图应用Darin Dimitrov 的回答,但在我的实现中 bindingContext.ModelName 等于“”。
这是我的视图模型:
public class UrunViewModel
{
public Urun Urun { get; set; }
public Type UrunType { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
这是发布模型类型的视图部分:
@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" ))
Run Code Online (Sandbox Code Playgroud)
这是我的自定义模型绑定器:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
最后,Global.asax.cs 中的行:
ModelBinders.Binders.Add(typeof(UrunViewModel), new UrunBinder());
Run Code Online (Sandbox Code Playgroud)
在被覆盖的CreateModel函数内部,在调试模式下,我可以看到它bindingContext.ModelName等于“”。而且,typeValue为空,因此CreateInstance功能失败。
我不认为您需要该bindingContext.ModelName财产来完成您想做的事情。
根据Darin Dimitrov 的回答,您似乎可以尝试以下操作。首先,您的表单上需要一个隐藏字段,用于输入以下类型:
@using (Html.BeginForm("UrunEkle", "Yonetici")) {
@Html.Hidden("UrunType", Model.Urun.GetType())
Run Code Online (Sandbox Code Playgroud)
然后在你的模型绑定中(基本上是从 Darin Dimitrov 复制的):
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;
}
Run Code Online (Sandbox Code Playgroud)
有关如何填充的更多信息,请参阅这篇文章bindingContext.ModelName。