Validating required selection in DropDownList

前端 未结 2 1795
萌比男神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:28

    One possible issue is that jQuery Validate does run any rules if the value of an element is empty.

    You can get around this by retriggering the validation when the user loses focus:

    // select statements not firing null validation automatically
    $("select").blur(function () { $(this).valid() });
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题