C# bindingContext.ModelName是否为空?
所以我尝试应用,但在我的实现中bindingContext.ModelName等于“” 以下是我的viewmodel:C# bindingContext.ModelName是否为空?,c#,asp.net-mvc-3,defaultmodelbinder,C#,Asp.net Mvc 3,Defaultmodelbinder,所以我尝试应用,但在我的实现中bindingContext.ModelName等于“” 以下是我的viewmodel: public class UrunViewModel { public Urun Urun { get; set; } public Type UrunType { get; set; } } 以下是视图中发布模型类型的部分: @model UrunViewModel @{ ViewBag.Title = "Tablo Ekle"; var
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" ))
最后,Global.asax.cs中的行:
ModelBinders.Binders.Add(typeof(UrunViewModel), new UrunBinder());
在被重写的
CreateModel
函数中,在调试模式下,我可以看到bindingContext.ModelName
等于“”。而且,typeValue
为空,因此CreateInstance
函数失败。我认为您不需要使用bindingContext.ModelName
属性来完成您试图执行的操作
顺便说一下,您可以尝试以下方法。首先,您需要在表单上为类型设置一个隐藏字段:
@using (Html.BeginForm("UrunEkle", "Yonetici")) {
@Html.Hidden("UrunType", Model.Urun.GetType())
然后在模型绑定中(基本上是从Darin Dimitrov复制的):
有关如何填充
bindingContext.ModelName
的更多信息,请参阅。bindingContext.ValueProvider.GetValue(“UrunType”)真正起作用。我还无法让它创建我想要的实例,但这是一个进步。谢谢。好的,我创建了这个实例,但是它的派生属性都是空的。只设置基类的属性
@using (Html.BeginForm("UrunEkle", "Yonetici")) {
@Html.Hidden("UrunType", Model.Urun.GetType())
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;
}