ASP .NET MVC - DropDownList OnChange

user2707729 picture user2707729 · Aug 29, 2013 · Viewed 9.8k times · Source

I want to hide some data when I select a value in my dropdownList.

Example :

When I choose Gender = M, I don't want to see in my Title : Mr. Only Miss or Madame.

Here is my code :

     @Html.DropDownListFor(m => m.Gender, new[] {
                           new SelectListItem() {Text = "M", Value = "M"},
                           new SelectListItem() {Text = "F", Value = "F"},
                           }, "---Choose Gender---", new { onchange = "Select();" })

     @Html.DropDownListFor(m => m.Title, new[] {
                           new SelectListItem() {Text = "Mister", Value = "Mr."},
                           new SelectListItem() {Text = "Madame", Value = "Mme."},
                           new SelectListItem() {Text = "Miss", Value = "Miss."}
                            }, "---Choose Title---")

In Javascript Section :

   function Select() {
        // the code.
    }

Answer

Karthik Bammidi picture Karthik Bammidi · Aug 29, 2013

You can do this with the help of JQuery,

  function changeGender()
    {
    if($('#Gender').val()=='M')
    {
    $('#Title').html('');
    $('#Title').html('<option value="Mister">Mr.</option>');
    }
    else if($('#Gender').val()=='F')
    {
    $('#Title').html('');
    $('#Title').html('<option value="Madame">Madam</option><option value="Miss">Miss.</option>');
    }
    else
    {
    $('#Title').html('');
    }
return false;
    }

Hope this helps.