gpt4 book ai didi

c# - bindingContext.ModelName 为空?

转载 作者:行者123 更新时间:2023-11-30 17:59:17 24 4
gpt4 key购买 nike

所以我正在尝试申请 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com