【问题标题】:bindingContext.ModelName is empty?bindingContext.ModelName 为空?
【发布时间】:2012-07-06 21:35:21
【问题描述】:

所以我尝试申请Darin Dimitrov's answer,但在我的实现中 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 函数失败。

【问题讨论】:

    标签: c# asp.net-mvc-3 defaultmodelbinder


    【解决方案1】:

    我认为您不需要 bindingContext.ModelName 属性来执行您正在尝试做的事情。

    通过Darin Dimitrov's answer,看来您可以尝试以下方法。首先,您需要在表单上为类型设置一个隐藏字段:

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

    然后在您的模型绑定中(基本上是从 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;
    }
    

    有关如何填充bindingContext.ModelName 的更多信息,请参阅this post

    【讨论】:

    • bindingContext.ValueProvider.GetValue("UrunType") 确实有效。我还不能让它创建我想要的实例,但这是一个进步。谢谢。
    • 好的,我设法创建了实例,但它的派生属性全部为空。只设置基类的属性
    猜你喜欢
    • 2012-12-15
    • 1970-01-01
    • 2014-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-24
    • 2012-01-04
    • 2020-08-12
    相关资源
    最近更新 更多