【问题标题】:Custom model binding returns default values自定义模型绑定返回默认值
【发布时间】:2011-07-22 10:07:49
【问题描述】:

我创建了一个继承自 DefaultModelBinder 的自定义模型绑定器,并重写了 BindProperty 方法以将“duration”属性设置为 35。

protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
    {
        if (propertyDescriptor.Name == "Duration")
        {
            var request = controllerContext.HttpContext.Request;
            var prefix = propertyDescriptor.Name;

            SetProperty(controllerContext, bindingContext, propertyDescriptor, 35);
        }
        base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
    }

此方法中的断点被击中,一切看起来都很好,但是当我的动作被击中后,我的模型又恢复为将 Duration 设置为默认值 0。

[HttpPost]
public ActionResult Create(ModelType model)
    { var val = model.Duration;
      //val = 0 :(
    }

我有点卡住了,请帮忙。

【问题讨论】:

    标签: asp.net-mvc-3 model-binding


    【解决方案1】:

    那是因为您正在调用基本方法。试试这样:

    protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
    {
        if (propertyDescriptor.Name == "Duration")
        {
            var request = controllerContext.HttpContext.Request;
            var prefix = propertyDescriptor.Name;
    
            SetProperty(controllerContext, bindingContext, propertyDescriptor, 35);
            return; // <!-- We have set the value so no need to continue any more
        }
    
        // This will be called for all other properties
        base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
    }
    

    【讨论】:

    猜你喜欢
    • 2022-01-01
    • 2018-10-13
    • 1970-01-01
    • 2018-08-22
    • 1970-01-01
    • 1970-01-01
    • 2017-10-31
    • 2022-12-16
    • 1970-01-01
    相关资源
    最近更新 更多