Asp.net mvc jquery validation dropdown

How can I check a dropdown with unobtrusive javascript? How to check it with a text field for the required validator, but it does not work for a drop-down list?

Need to modify an unobtrusive js file? or is there another option for checking the dropdown list?

I want to show errors when I checked form.validate () in my javascript.

+3
source share
6 answers
    $(function () {
        $("#form1").validate({
            rules: {
                ProductCategoryList: {
                    required: true
                }

            },
            messages: {
                ProductCategoryList: {
                    required: "This field is required"
                }
            }
        });
    });
+1
source
0
source

 <p>
        <label for="ProductCategoryList">Product Categories</label>
        <%= Html.DropDownList("ProductCategoryList", ViewData["ProductCategories"] as SelectList)%>
    </p>

script

        $.validator.addMethod("selectNone",
            function (value, element) {
                return this.optional(element) || element.selectedIndex != 0;
            },
           "Please select an option."
        );


        $(function () {
            $("#form1").validate({
                rules: {
                    ProductCategoryList: {
                        selectNone: true
                    }

                },
                messages: {
                    ProductCategoryList: {
                        selectNone: "This field is required"
                    }
                }
            });
        });
0

, Viewmodel, DropDownList. :

:

        <div class="editor-field">
           @Html.DropDownListFor(model => model.SelectedPlantID,
                                 new SelectList(Model.Plants, "Value", "Text"),
                                 " ", new { id = "ddlPlant" })

          @Html.ValidationMessageFor(model => model.SelectedPlantID)
    </div>

ViewModel ( ):

            private List<SelectListItem> _plants = new List<SelectListItem>();
    [Required]
    [Display(Name = "Plant")]
    public List<SelectListItem> Plants
    {
        get
        {
            return (_plants);
        }

        set
        {
            _plants = value;
        }
    }

    public Guid SelectedPlantID
    {
        get;
        set;
    }

: SelectedPlantID .

, !

0

value="", .

<asp:ListItem Value="">- Select Something -</asp:ListItem>
0

jQuery,

DropDownListFor not DropDownList

@Html.DropDownListFor(c => c.Profile_Id, null, "-- Choose --", new { @class = "input-large" })

, , ViewBag.Profile_Is as SelectList, , .

0

Source: https://habr.com/ru/post/1782391/


All Articles