Skip to content

MVC DropDownList onchange event with value

I’m pretty new to MVC and i’m trying to determine the value of a DropDownList when the value is changed. At the moment the val variable being passed to my javascript function is always ‘undefined’. I’ve googled for the solution and everywhere says to do exactly what i’m doing right now. What am i doing wrong?

cshtml:

@Html.DropDownListFor(m => m.NearestDealers
     , new SelectListItem[] 
     { new SelectListItem() {
               Text = "No nearest dealers", Value = "0"
          },
          new SelectListItem() {
               Text = "1", Value = "1"
          },
          new SelectListItem() {
               Text = "2", Value = "2"
          },
          new SelectListItem() {
               Text = "3", Value = "3"
          } 
      }, new { onchange = "onNearestDealersChange(this.Value);"})

And my javascript:

function onNearestDealersChange(val) {
    if (val == 0) {
        $("#dealer-pools").addClass("hidden");
    } else {
        $("#dealer-pools").removeClass("hidden");
    }
}

Answer

Try using a lower case ‘v’ for ‘this.Value’

new { onchange = "onNearestDealersChange(this.value);"}