自定义模型绑定器继承自 DefaultModelBinder [英] Custom Model Binder inheriting from DefaultModelBinder

查看:23
本文介绍了自定义模型绑定器继承自 DefaultModelBinder的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm attempting to build a custom model binder for MVC 4 that will inherit from DefaultModelBinder. I'd like it to intercept any interfaces at any binding level and attempt to load the desired type from a hidden field called AssemblyQualifiedName.

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

Here's what I have so far (simplified):

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 文件(简化):

Example Create.cshtml file (simplified):

@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(接口).

The above partial _JobParameters.cshtml looks at the Model.Job's properties and builds the edit controls, similar to @Html.EditorFor(), but with some extra markup. The ScheduledJob.Job property is of type IJob (interface).

示例 ScheduledJobsController.cs(简化版):

Example ScheduledJobsController.cs (simplified):

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

当我保存表单时,它会正确解释对象类型并获取一个新实例,但是对象的属性没有设置为其适当的值.

When I save the form, it interprets the object type correctly and gets a new instance, but the properties of the object are not being set to their appropriate values.

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

What else do I need to do to this to tell the default binder to take over the property binding of the specified type?

推荐答案

这篇文章 告诉我我过度复杂化了模型绑定器.以下代码有效:

This article showed me that I was over-complicating the model binder. The following code works:

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

这篇关于自定义模型绑定器继承自 DefaultModelBinder的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆