0

I have Institutes collection. it contains ID, Description, Name, Age etc properties. I can get ID and Description after selection. but how to get other properties (e.g. Name) based on selection. here, I need "Name" property as well.

I have below onchange function written in javascript . I have to get "Name" property value. I dont want to call server logic again -

$("#InstituteID").change(function() {
// Need some logic to get Name value

});

Dropdownlist code -

@Html.DropDownList("InstituteID",
                       new SelectList(
                           ViewBag.Institutes,
                           "ID",
                           "Description"
                       ),
                "-- Institute Type --", new { @class = "form-control" })
SSD
  • 1,041
  • 3
  • 19
  • 39

1 Answers1

1

you can use the data-attributes property of select tag options.

You have to modify HTML markup like this:

@{
 var Institutes = new List<Institutes>() {
 new Institutes(){ ID=1,Description="test1",Name="name1",age=20 },
 new Institutes(){ ID=2,Description="test2",Name="name2",age=21 },
 new Institutes(){ ID=3,Description="test3",Name="name3",age=22 }
 };
}

<select name="InstituteID" id="InstituteID">
@foreach (var item in Institutes)
{
    <option data-name="@item.Name" data-age="@item.age" value="@item.ID">@item.Description</option>
}
</select>

Javascript will look like:

<script>
$(document).ready(function () {

    $("#InstituteID").change(function () {
        var element = $(this).find('option:selected');
        var name = element.attr("data-name");
        var name = element.attr("data-age");
        console.log("selected name is:"+ name);
    });
})
tajinder singh
  • 113
  • 1
  • 10