gpt4 book ai didi

c# - 继承自 DefaultModelBinder 的自定义模型绑定(bind)器

转载 作者:可可西里 更新时间:2023-11-01 02:59:40 25 4
gpt4 key购买 nike

我正在尝试为 MVC 4 构建自定义模型绑定(bind)器,它将继承自 DefaultModelBinder。我希望它在任何 绑定(bind)级别拦截任何接口(interface),并尝试从名为 AssemblyQualifiedName 的隐藏字段中加载所需的类型。

这是我目前所拥有的(已简化):

public class MyWebApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
ModelBinders.Binders.DefaultBinder = new InterfaceModelBinder();
}
}

public class InterfaceModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext,
ModelBindingContext bindingContext)
{
if (bindingContext.ModelType.IsInterface
&& controllerContext.RequestContext.HttpContext.Request.Form.AllKeys.Contains("AssemblyQualifiedName"))
{
ModelBindingContext context = new ModelBindingContext(bindingContext);

var item = Activator.CreateInstance(
Type.GetType(controllerContext.RequestContext.HttpContext.Request.Form["AssemblyQualifiedName"]));

Func<object> modelAccessor = () => item;
context.ModelMetadata = new ModelMetadata(new DataAnnotationsModelMetadataProvider(),
bindingContext.ModelMetadata.ContainerType, modelAccessor, item.GetType(), bindingContext.ModelName);

return base.BindModel(controllerContext, context);
}

return base.BindModel(controllerContext, bindingContext);
}
}

示例 Create.cshtml 文件(已简化):

@model Models.ScheduledJob

@* Begin Form *@
@Html.Hidden("AssemblyQualifiedName", Model.Job.GetType().AssemblyQualifiedName)

@Html.Partial("_JobParameters")
@* End Form *@

上面的部分 _JobParameters.cshtml 查看 Model.Job 的属性并构建编辑控件,类似于 @Html.EditorFor(),但有一些额外的标记。 ScheduledJob.Job 属性的类型为 IJob(接口(interface))。

示例 ScheduledJobsController.cs(简化版):

[HttpPost]
public ActionResult Create(ScheduledJob scheduledJob)
{
//scheduledJob.Job here is not null, but has only default values
}

当我保存表单时,它正确地解释了对象类型并获得了一个新实例,但是对象的属性没有被设置为它们适当的值。

我还需要做些什么来告诉默认绑定(bind)器接管指定类型的属性绑定(bind)?

最佳答案

This article向我展示了我过度复杂化了模型 Binder 。以下代码有效:

public class InterfaceModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
if (bindingContext.ModelType.IsInterface)
{
Type desiredType = Type.GetType(
EncryptionService.Decrypt(
(string)bindingContext.ValueProvider.GetValue("AssemblyQualifiedName").ConvertTo(typeof(string))));
bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, desiredType);
}

return base.BindModel(controllerContext, bindingContext);
}
}

关于c# - 继承自 DefaultModelBinder 的自定义模型绑定(bind)器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16747320/

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