web-dev-qa-db-ja.com

DropDownListで必要な選択を検証する

私のビューモデルは、コンボボックスとして表示する必要があるプロパティを定義しています。プロパティの定義は次のとおりです。

[Required]
public int Processor { get; set; }

コンボボックスをレンダリングするためにDropDownListForを使用しています。

<%=Html.DropDownListFor(r => r.Processor, Model.Processors, Model.Processor)%>

Model.ProcessorsにはIEnumerable<SelectListItem>が含まれ、1つの特別な項目が次のように定義されています。

var noSelection = new SelectListItem
  {
    Text = String.Empty,
    Value = "0"
  };

次に、コンボボックスに検証を追加して、ユーザーが「noSelection」とは異なる値を選択する必要があるようにする必要があります。 RequiredAttributeの設定を希望しましたが、デフォルト値の設定がありません。

18
Ladislav Mrnka

これはどう:

[Required]
public int? Processor { get; set; }

その後:

<%= Html.DropDownListFor(
    x => x.Processor, Model.Processors, "-- select processor --"
) %>

そしてあなたのPOSTアクションで

[HttpPost]
public ActionResult Index(MyViewModel model)
{
    if (ModelState.IsValid)
    {
        // the model is valid => you can safely use model.Processor.Value here:
        int processor = model.Processor.Value;
        // TODO: do something with this value
    }
    ...
}

これで、noSelectionアイテムを手動で追加する必要がなくなりました。適切な DropDownListFor オーバーロードを使用するだけです。

26
Darin Dimitrov

考えられる問題の1つは、jQuery Validateが 要素の値が空の場合は任意のルールを実行する を実行することです。

これを回避するには、ユーザーがフォーカスを失ったときに 検証を再トリガーする

// select statements not firing null validation automatically
$("select").blur(function () { $(this).valid() });
0
KyleMit