Validating required selection in DropDownList

前端 未结 2 1802
萌比男神i
萌比男神i 2020-12-06 04:59

My view model defines property which has to be displayed as combo box. Property definition is:

[Required]
public int Processor { get; set; }
<
2条回答
  •  半阙折子戏
    2020-12-06 05:38

    How about this:

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

    And then:

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

    And in your POST action

    [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
        }
        ...
    }
    

    And now you no longer need to manually add the noSelection item. Just use the proper DropDownListFor overload.

提交回复
热议问题