c# - bindingContext.ModelName 为空?

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

所以我正在尝试申请 Darin Dimitrov's answer ,但在我的实现中 bindingContext.ModelName 等于“”。

这是我的 View 模型:

public class UrunViewModel
{
    public Urun Urun { get; set; }
    public Type UrunType { get; set; }
}

这是发布模型类型的 View 部分:

@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" ))

这是我的自定义模型 Binder :

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 函数中,在 Debug模式下我可以看到 bindingContext.ModelName 等于“”。而且,typeValue 为 null,因此 CreateInstance 函数失败。

最佳答案

我认为您不需要 bindingContext.ModelName 属性来完成您要执行的操作。

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

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

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

参见 this post有关如何填充 bindingContext.ModelName 的更多信息。

关于c# - bindingContext.ModelName 为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11369951/

相关文章:

c# - 正则表达式回溯与更改和空白

c# sql 插入。使用未分配的局部变量?

面向初学者的 C# GUI 编程 : Where to start?

model-view-controller - BindModel() 实现应该做什么?

c# - jQuery 中的 ConfigurationManager.AppSettings

c# - ColorConverter ConvertFromString 返回错误的名称

c# - DevExpress MVC GridView BindToLINQ() 选择了太多数据

sql - ASP.Net MVC3 SQL 连接字符串

asp.net-mvc - 带有表单和列表的 MVC 3 : default model binder and EditorFor

asp.net-mvc - DefaultModelBinder 嵌套级别+其他绑定(bind)器的问题