【问题标题】:Pass empty string as nullable int property将空字符串作为可为空的 int 属性传递
【发布时间】:2012-02-04 01:08:58
【问题描述】:

我的模特:

[DisplayName("Height")]
public int? Height { get; set; }

[DisplayName("Width")]
public int? Width { get; set; }

查看:

<%= Html.TextBoxFor(x => x.Width) %>
<%= Html.TextBoxFor(x => x.Height) %>

行动:

if (ModelState.IsValid)
    SaveSettings(model);

当从视图传递空字符串时,ModelState 为 false,但我需要空字符串作为有效输入,以便传递 nulls 并且 ModelState.IsValid 将为 true。我可以在视图中添加什么来添加此逻辑?或者也许有任何其他解决方案?非常感谢您的帮助。

【问题讨论】:

    标签: asp.net asp.net-mvc


    【解决方案1】:

    有一些变通方法,例如在 ViewModel 上使用字符串属性并使用 RegEx 验证器来确保它是一个数字。正则表达式不应触发空输入。然后,当您从 ViewModel 转到 Model 时,您必须对字符串值进行条件处理,例如

     var m = new Model();
     m.Property = !String.IsNullOrEmpty(this.Property)? int.parse(this.Property) as int?:null;
    

    【讨论】:

      【解决方案2】:

      int? (Nullable&lt;int&gt;) 永远无法接受空字符串。并且空字符串既不是null 也不是int 值(这是Nullable&lt;int&gt; 的要求)。

      如果您想拦截这种行为,您可以通过实现IModelBinder 或子类DefaultModelBinder 来设计您自己的自定义模型绑定器。这样做,你可以设置一个空字符串值等于null(或一些幻数,但我更喜欢null)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-08-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-07
        相关资源
        最近更新 更多