Reputation: 117
What's the correct way to bind the selected value to dropdown list generated using @Html.DropDownList from controller. i.e. selection of dropdown should occur from controller side. This how I have generated the dropdown.
@Html.DropDownList("CountryFilter", (IEnumerable<SelectListItem>)ViewBag.Coutries, "Select", new { id = "CountryFilter" })
My approch - I tried updating the value using jquery by using id selector but I was unable to receive the value to be selected from controller in OnPageload method like this
$(document).ready(function () {
$('[data-toggle="tooltip"]').tooltip();
$('#RoleFilter').val(@ViewBag.roleFilter.ToString());
});
It worked when I hardcoded the value like this
$('#RoleFilter').val("3");
But I was unable to get the value from ViewBag.
My issue can be resolved in two ways
Upvotes: 1
Views: 523
Reputation: 629
If your code worked when you hardcoded the value, then must try the below code for getting value in ViewBag
$(document).ready(function () {
$('[data-toggle="tooltip"]').tooltip();
$('#RoleFilter').val(@Html.Raw(@ViewBag.roleFilter.ToString())); //Accessing the Json Object from ViewBag
});
Upvotes: 0