简体   繁体   中英

Dropdown validation fails in MVC 5

My code is like this. inside model

[Required]
    public int ProcedureCategoryID { get; set; }
    public virtual ProcedureCategory ProcedureCategory { get; set; }

Inside COntroller

  ViewBag.ProcedureCategoryList = new SelectList(db.ProcedureCategories.Where(x => !x.IsMainCat),
            "ProcedureCategoryID", "Name");

In View (Edit)

     @Html.DropDownList("ProcedureCategoryID", (SelectList)ViewBag.ProcedureCategoryList, "--Select Sub Category--", new { @class = "form-control", @id = "SubCat" })
  @Html.ValidationMessageFor(model => model.ProcedureCategoryID)

And this dropdown data is dynamically added by jquery like this

 $('#MainCat').change(function () {
            var selectedValue = $('#MainCat').val();
            $.post('@Url.Action("GetSubCategory", "Procedure")', { id: selectedValue }, function (data) {
                $("#SubCat").empty();
                var optionhtml1 = '<option value="' +
                0 + '">' + "--Select Sub Category--" + '</option>';
                $("#SubCat").append(optionhtml1);

                $.each(data, function (i) {
                    var optionhtml = '<option value="' +
                data[i].ProcedureCategoryID + '">' + data[i].Name + '</option>';
                    $("#SubCat").append(optionhtml);
                });

            });
        });

Everything looks okay to me, But the required validation is not happening for this dropdown.Can anyone point out what I am doing wrong?

The first option you have added in the ajax call has a value of 0 which is a valid integer so it passes validation.

Instead use

var select = $("#SubCat");
select.empty().append($('<option></option>').val('').text('--Select Sub Category--'));
$.each(data, function (index, item) {
  select.append($('<option></option>').val(item.ProcedureCategoryID).text(item.Name));
});

which will add the first option with a null value.

You should also change the property to nullable int

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM