简体   繁体   中英

client side validation of <select> in asp.net MVC 4

I am working on asp.net MVC application. I have a dropdown like this in my razor view:

 <select id="ddlAreaID">
 @foreach (var item in Model.Areas)
 {
     <optgroup label="@item.CityName">
     @foreach (var val in item.Areas)
     {
         var selected = (val.AreaID == Model.AreaID) ? "selected=selected" : string.Empty;
         <option value="@val.AreaID" @selected>@val.AreaName</option>
     }
     </optgroup>
 }
 </select>
 @Html.HiddenFor(m => m.AreaID)

I have added first item to collection like this:

Areas.Insert(0, new CityInfo() 
{
    Areas = new List<AreaInfo>() 
    { 
        new AreaInfo() 
        { 
            AreaID = 0, 
            AreaName = "select an Area" , 
            CityName = "" 
        }
    }  
});

I want to perform client validation of this select/drop down so that at least one item is selected. How can I do this ?

Please suggest.

You should start refactoring your view model and your view. Your current design is pretty static and has some coupling issues. For example it already looks wrong to create an area, named "Select an area!".

I don't know how your view model is named, but for example concerncs, I will call it ViewModel . The view model represents the data of the view. So in your use case, you wish to select an area. There is a predefined set of areas you give the view to render the drop-down. And you wish to get back the user selection. Therefor you will end with two properties, representing this data:

public class ViewModel
{
    public List<AreaModel> AvailableAreas { get; set; }

    public AreaModel SelectedArea { get; set; }
}

Since AvailableAreas is required to build up the view, you can define a constructor that accepts a list of areas to initialize the property. However, this is not mandatory.

In your view you can now use helpers to make generate your drop down list:

@Html.DropDownListFor(m => m.SelectedArea, Model.AvailableAreas, "Select an area")

This really simplifies your view! And now you can also use data annotations to enable client-side validation:

public class ViewModel
{
    public List<AreaModel> AvailableAreas { get; set; }

    [Required]
    public AreaModel SelectedArea { get; set; }
}

This should get you into the right direction. However, I still see some problems with your option groups. If you are forced to use them, here is something to read on: Consuming a Helper code for optgroup functionality in Asp.net MVC .

You could use jQuery to validate that the selected index is greater than 0 before submitting the form. Something like

$("form").submit(function(){
     if($("#ddlAreaID")[0].selectedIndex === 0) {
         // display error message
         return false;
     }
     return true; 
});
so that at least one item is selected

Looking at your dropdownlist, it's not a multiple select. Any dropdownlist (that has options inside it) always has a value selected (unless specified, it selects the first element by default).

Also, it can't have more than one value selected (since it's not a multiple select).

In your code snippet, I don't see you adding a dummy either (eg an option labeled "Please select one option").

If I take your question to the letter, you don't need any validation.

Now I'm going to assume that a dummy option will be added, and you want to validate that the user has selected any option except the dummy .

First: add the dummy.

<select id="ddlAreaID">

    <!-- This is the dummy. Note that its value is "dummy" -->
    <option value="dummy">Please select an area...</option>

 @foreach (var item in Model.Areas)
 {
     <optgroup label="@item.CityName">
     @foreach (var val in item.Areas)
     {
         var selected = (val.AreaID == Model.AreaID) ? "selected=selected" : string.Empty;
         <option value="@val.AreaID" @selected>@val.AreaName</option>
     }
     </optgroup>
 }
</select>

Your selectlist (presumably) gets posted back via a form. So what you'll want to do is:

  • When the form is submitted, catch it before it submits.
  • Check that the dummy wasn't selected
  • If everything is okay, the form can be submitted.
  • If validation fails, do not submit the form.

I'm assuming your form has an id ( #myForm , by way of example).

$("#myForm").submit( function (event) {

    //The form has not yet submitted, and it is waiting for this function to complete.

    if( $("#ddlAreaID").val() === "dummy" ) //this needs to match the value you gave the dummy option
    {
        alert("You did not choose an area!");

        event.preventDefault(); //this line makes sure the form does not get submitted.
    }

    //If everything is still okay, we can simply exit the function. Form submission will continue.
});

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