0

わかりました、次の設定があります。

モデル

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>

これは問題なく機能します。タッチに合格しないと、検証が開始されず、ページの投稿ボタンをクリックできます。

ただし、リストに「 -- 選択してください -- 」項目を実装しようとすると、検証が行われ、投稿ボタンの 1 つをクリックできなくなります。ブー!!

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

このような特定の要件については、簡単な方法は、値を as として-- Please Select --新しいものとして追加することだと思います。List ItemSupplyTypID0

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 に答える