好的dokey,我有以下设置。
模型
public class SupplyType
{
[Key]
public int SupplyTypeId { get; set; }
public string SupplyTypeName { get; set; }
}
public class Supply
{
[Display(Name = "What type of supply is this from?")]
public int SupplyTypeId { get; set; }
public IEnumerable<SupplyType> SupplyType { get; set; }
}
控制器
public ActionResult (Guid id)
{
var model = Model(id);
model.Supply.SupplyType = db.SupplyTypes.ToList();
return View(model.);
}
我现在有查看以下
//Good view
<div class="editor-label">
@Html.LabelFor(model => model.SupplyTypeId, "SupplyType")
</div>
<div class="editor-field">
@Html.DropDownListFor(x => x.SupplyTypeId, new SelectList(Model.SupplyType, "SupplyTypeId", "SupplyTypeName"))
@Html.ValidationMessageFor(model => model.SupplyTypeId)
</div>
如果我没有通过触摸它,这工作正常和花花公子,然后验证不会触发,我可以点击我页面上的帖子按钮。
然而,当我尝试在列表中实现“ - 请选择 - ”项目时,验证结果发生了,我被卡住了,无法点击我的一个帖子按钮.bo !!“ p>
//Bad view
<div class="editor-label">
@Html.LabelFor(model => model.SupplyTypeId, "SupplyType")
</div>
<div class="editor-field">
@Html.DropDownListFor(x => x.SupplyTypeId, new SelectList(Model.SupplyType, "SupplyTypeId", "SupplyTypeName"), " -- Please Select -- ")
@Html.ValidationMessageFor(model => model.SupplyTypeId)
</div>
我仍然需要在下拉菜单中输入“ - 请选择 - ”项,但如果尚未设置验证,我不希望验证。
关于如何在不完全关闭验证的情况下解决这个问题的任何想法?原因是下拉列表将有条件地显示,因此可能不需要填充。
任何帮助都很受欢迎。
答案 0 :(得分:1)
对于您这样的具体要求,我认为简单的方法是将-- Please Select --
添加为List Item
,其SupplyTypID
值为0
。
public ActionResult (Guid id)
{
var model = Model(id);
model.Supply.SupplyType = db.SupplyTypes.ToList();
model.Supply.SupplyType.Add(new
{
SupplyTypID=0, SupplyTypeName=" Please Select"
});
return View(model);
}