bindingContext.ModelName is empty?



所以我试图应用Darin Dimitrov的答案,但在我的实现中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.ModelName属性来完成您要做的事情。

根据达林·季米特洛夫的回答,看起来您可以尝试以下方法。 首先,您需要在表单上为该类型设置一个隐藏字段:

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

有关如何填充bindingContext.ModelName的详细信息,请参阅此帖子。

最新更新