0

好的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>

这工作得很好而且花花公子,如果我不通过触摸它,那么验证不会触发,我可以点击我页面上的发布按钮。

但是,当我尝试在列表中实施“-请选择--”项目时,验证会发生并且我被卡住了,无法单击我的帖子按钮之一..嘘!

 //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>

我仍然需要下拉菜单中的“-- Please Select --”项,但如果尚未设置,我不希望验证生效。

关于如何在不完全关闭验证的情况下解决这个问题的任何想法?这样做的原因是下拉列表将有条件地显示,因此可能不需要填充。

任何帮助都得到了很大的帮助。

4

1 回答 1

2

对于您这样的特定要求,我认为简单的方法是添加-- Please Select --为新List ItemSupplyTypIDas 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);    
}
于 2012-07-16T16:08:35.580 回答