对于空字符串字段,ModelState.IsValid为false

时间:2012-02-07 22:55:00

标签: asp.net asp.net-mvc-2

我的模型字段接受数字和空字符串:

[DisplayName("Height")]
[RegularExpression (@"^\d*$", ErrorMessage="Height must be a number or left out   blank")]
public string Height { get; set; }

[DisplayName("Width")]
[RegularExpression(@"^\d*$", ErrorMessage = "Height must be a number or left out blank")]
public string Width { get; set; }

我的观点:

<%= Html.LabelFor(x => x.Width) %>:
<%= Html.TextBoxFor(x => x.Width) %>

<%= Html.LabelFor(x => x.Height) %>:
<%= Html.TextBoxFor(x => x.Height) %>

在控制器操作中:

[HttpPost]

public ActionResult Edit(MyModeltype model)
{
    model.Width = String.IsNullOrEmpty(model.Width) ? "" : model.Width; //NEEDED?
    model.Height = String.IsNullOrEmpty(model.Height) ? "" : model.Height; //NEEDED?

    if (ModelState.IsValid)
        SaveSettings(model);

    return View("SomeView");
}

当我提供空文本框时,Model.Width和.Height作为空值传递,ModelState.IsValid为false。我只需要能够传递空字符串。省略正则表达式属性时,同样的问题,所以它不是正则表达式。谢谢!

2 个答案:

答案 0 :(得分:0)

我没有看到您在视图中显示错误消息。所以这可能会导致问题,但我不确定。无论如何尝试这个,看看它是否有效:

<%= Html.LabelFor(x => x.Width) %>:
<%= Html.TextBoxFor(x => x.Width) %>
<%= Html.ValidationMessageFor(x => x.Width) %>

<%= Html.LabelFor(x => x.Height) %>:
<%= Html.TextBoxFor(x => x.Height) %>
<%= Html.ValidationMessageFor(x => x.Height) %>

答案 1 :(得分:0)

尝试将DisplayFormat属性添加到模型的属性中:

[DisplayFormat(ConvertEmptyStringToNull = false)]
[DisplayName("Height")]
[RegularExpression (@"^\d*$", ErrorMessage="Height must be a number or left out   blank")]
public string Height { get; set; }

[DisplayFormat(ConvertEmptyStringToNull = false)]
[DisplayName("Width")]
[RegularExpression(@"^\d*$", ErrorMessage = "Height must be a number or left out blank")]
public string Width { get; set; }

这将确保空文本框值不会转换为NULL。

或者,您可以显式定义getter和setter以将null转换为空字符串:

private string _width;
public string Width
{
    get { return _width ?? string.Empty; }
    set { _width = value ?? string.Empty; }
}