在我的模特中我有
[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>
我的问题是,如果输入大于零的数字,此代码正常工作,但如果我输入零,则显示所需的错误。 我想插入零作为默认值。我如何在我的代码中做到这一点。
答案 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; }
你可以这样使用吗?