Asp.net mvc 如何插入“;请选择";项目进入MVC下拉列表,但不会导致验证
好的,dokey,我有以下设置 型号Asp.net mvc 如何插入“;请选择";项目进入MVC下拉列表,但不会导致验证,asp.net-mvc,asp.net-mvc-3,validation,drop-down-menu,Asp.net Mvc,Asp.net Mvc 3,Validation,Drop Down Menu,好的,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 SupplyT
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; }
}
我现在对以下内容有了的看法
//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>
//视野好
@LabelFor(model=>model.SupplyTypeId,“SupplyType”)
@DropDownListFor(x=>x.SupplyTypeId,新选择列表(Model.SupplyType,“SupplyTypeId”,“SupplyTypeName”))
@Html.ValidationMessageFor(model=>model.SupplyTypeId)
这很好用,如果我不通过触摸,验证就不会启动,我可以点击页面上的post按钮
但是,当我尝试在列表中实现一个“--请选择--”项时,验证突然出现,我被卡住了,无法单击我的一个post按钮..boo
//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>
//视图不正确
@LabelFor(model=>model.SupplyTypeId,“SupplyType”)
@DropDownListFor(x=>x.SupplyTypeId,新选择列表(Model.SupplyType,“SupplyTypeId”,“SupplyTypeName”),“--请选择--”)
@Html.ValidationMessageFor(model=>model.SupplyTypeId)
我仍然需要一个“--请在下拉列表中选择--”项,但如果未设置此项,我不希望执行验证
你知道我如何在不完全关闭验证的情况下解决这个问题吗?原因是下拉列表将有条件地显示,因此可能不需要填充
非常感谢您的帮助。对于您这样的特定需求,我认为简单的方法是添加
——请选择--
作为新的列表项,并将SupplyTypeId
值设置为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);
}
最重要的是Shyju(虽然我最后做了一个insert,将索引设置为O)。你能解释一下为什么验证会在坏视图方法中触发,而不是在你将它弹出到模型中时触发吗?我想不通。你所说的坏视图方法是什么意思?[1]:[2]:
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);
}