【问题标题】:c# custom model binder for specific model and specific variable typec# 用于特定模型和特定变量类型的自定义模型绑定器
【发布时间】:2014-11-04 21:10:17
【问题描述】:

我自己对可空整数和验证文本有疑问。

基本上我想更改未提供可为空的 int 时显示的验证消息

所以从

"The value 'xxxxxxxxxxxxxxxxxxxx' is invalid" 

"Please provide a valid number"

我自己有一个像这样的自定义模型绑定器

public class IntModelBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var integerValue = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
            if (integerValue == null || integerValue.AttemptedValue == "")
                return null;

            var integer = integerValue.AttemptedValue;

            bindingContext.ModelState.SetModelValue(bindingContext.ModelName, bindingContext.ValueProvider.GetValue(bindingContext.ModelName));
            try
            {
                return int.Parse(integer);
            }
            catch (Exception)
            {
                bindingContext.ModelState.AddModelError(bindingContext.ModelName, String.Format("\"{0}\" is invalid, please provide a valid number.", bindingContext.ModelName));
                return null;
            }
        }
    }

现在我已经更新了我的 global.asax.cs,所以所有可以为空的整数都使用这个模型绑定器,但是我不希望所有可以为空的整数都使用它,我只想要一个特定的模型来使用它并且只使用我的模型绑定器在该模型中的可为空整数上。有没有办法可以将此模型绑定器绑定到我的模型,并且只与可为空的 int 变量关联?

我曾尝试像这样在我的模型上使用我的模式绑定器

[ModelBinder(typeof(IntModelBinder))]
public class CreateQuoteModel
{
    ....
}

但它不检查可为空的整数,我想避免使用第三方插件

【问题讨论】:

    标签: c# asp.net-mvc


    【解决方案1】:

    您在可为空的整数上返回 null

    if (integerValue == null || integerValue.AttemptedValue == "")
       return null;
    

    所以您不会将该错误添加到可空整数的模型状态中。
    另外我建议你使用

    int result=0;
    if(!int.TryParse(integer, out result)){
       bindingContext.ModelState.AddModelError(bindingContext.ModelName, String.Format("\"{0}\" is invalid, please provide a valid number.", bindingContext.ModelName));
       return null;
    }
    return result;
    

    而不是您的异常处理流程来避免这种反模式

    【讨论】:

    • 感谢您的回答,但这并不能解决我的实际问题
    【解决方案2】:

    只要您的模型上有一个可为空的 int 并且带有自定义消息的所需属性,这肯定会起作用吗?

    相反,您可以使用正则表达式匹配来检查长度和类型

    【讨论】:

    • 这不起作用,因为模型绑定器接管了所有值检查,因此它错过了模型内部的所有字符串和日期时间
    • 我不确定你的意思?您将属性添加到为您验证它们的所有必填字段。如果您需要自定义行为,请创建自定义属性并使用适当的接口。
    猜你喜欢
    • 1970-01-01
    • 2011-02-08
    • 2021-09-17
    • 2019-12-07
    • 1970-01-01
    • 1970-01-01
    • 2012-07-31
    • 1970-01-01
    • 2012-02-18
    相关资源
    最近更新 更多