如何在mvc </int>中的Required Nullable <int>类型中插入零

时间:2015-02-24 09:03:57

标签: asp.net-mvc data-annotations

在我的模特中我有

[Required(ErrorMessage="How Many Child Do You Have?")]
[Display(Name ="No Of Children")]
public Nullable<int> NoOFChildren { get; set; }

在我看来,我使用以下代码

<div class="col-sm-5">
  <div class="form-group">
    <div class="col-lg-3">
      @Html.LabelFor(model => model.NoOFChildren, new { @class = "control-label" })
    </div>
    <div class="col-lg-6">
      @Html.EditorFor(model => model.NoOFChildren, new { htmlAttributes = new { @class = "form-control", placeholder = "No Of Children" } })
    </div>
    <div class="col-lg-3">
      @Html.ValidationMessageFor(model => model.NoOFChildren, "", new { @class = "text-danger" })
    </div>
  </div>
</div>

我的问题是,如果输入大于零的数字,此代码正常工作,但如果我输入零,则显示所需的错误。 我想插入零作为默认值。我如何在我的代码中做到这一点。

2 个答案:

答案 0 :(得分:0)

如何使用:

 @Html.EditorFor(model => model.NoOFChildren, new { htmlAttributes = new { @class = "form-control", placeholder = "No Of Children", value=0 } })

,您可能想要为属性

创建自定义验证

在控制器/模型中使用默认值填充模型

控制器:

public ActionResult YourAction(){
var model = new Model(){
  NoOFChildren=0
}
return View(model);
}

或模型构造函数

public class Model{
  public Model(){
    NoOFChildren=0;  // not the best solution as you might want to reuse the model
  }

答案 1 :(得分:-1)

[Required(ErrorMessage="How Many Child Do You Have?")]
[Display(Name ="No Of Children")]
[DefaultValue(0)]
public Nullable<int> NoOFChildren { get; set; }
你可以这样使用吗?