c# - .Net MVC3 自定义模型绑定(bind)器 - 初始加载模型

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

我正在创建一个自定义模型绑定(bind)器,以便在使用传入值更新模型之前首先从数据库加载模型。 (继承自DefaultModelBinder)

我需要重写哪个方法才能执行此操作?

最佳答案

您需要重写DefaultModelBinder基类的BindModel方法:

    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        if (bindingContext.ModelType == typeof(YourType))
        {
            var instanceOfYourType = ...; 
            // load YourType from DB etc..

            var newBindingContext = new ModelBindingContext
            {
                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => instanceOfYourType, typeof(YourType)),
                ModelState = bindingContext.ModelState,
                FallbackToEmptyPrefix = bindingContext.FallbackToEmptyPrefix,
                ModelName = bindingContext.FallbackToEmptyPrefix ? string.Empty : bindingContext.ModelName,
                ValueProvider = bindingContext.ValueProvider,
            };
            if (base.OnModelUpdating(controllerContext, newBindingContext)) // start loading..
            {
                // bind all properties:
                base.BindProperty(controllerContext, bindingContext, TypeDescriptor.GetProperties(typeof(YourType)).Find("Property1", false));
                base.BindProperty(controllerContext, bindingContext, TypeDescriptor.GetProperties(typeof(YourType)).Find("Property2", false));

                // trigger the validators:
                base.OnModelUpdated(controllerContext, newBindingContext);
            }

            return instanceOfYourType;
        }            
        throw new InvalidOperationException("Supports only YourType objects");
    } 

关于c# - .Net MVC3 自定义模型绑定(bind)器 - 初始加载模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6207477/

相关文章:

c# - 如何在 ASP Core 中使用 HttpGet 指定默认 View

c# - 如何从 C# 中的二进制文件中检索整数值

c# - 为什么将字符串从 C# 传递到 C++ dll 会得到 NULL?

.net - 在 .net 4.5 中并行化 for 循环

asp.net-mvc - 我使用 AntiXSS 但我仍然可以破解页面

c# - 根据父元素属性选择第n个子元素

.net - mvc 日志记录 : [LogRequest] vs OnActionExecuting

c# - 如何在 WPF 应用程序中动态导入 3D 模型

asp.net-mvc - 有和没有 pageBaseType 的页面配置部分有什么区别

.net - 不使用 SSL 的 WCF 安全性