Skip to content Skip to sidebar Skip to footer

DropdownListfor To Be Auto Selected On The Basis Of A Value Of String Asp.net Mvc

I have one string and one list proeprty in my model public string _drinkType { get; set; } public List _drinkTypeDropDown { get; set; } in my view @Html.Dr

Solution 1:

You can set a ViewBag property with the possible options in the controller and the model can keep only the property which will hold the actual value. In your controller, add the value to ViewBag:

ViewBag.DrinkTypeDropDown = new List<SelectListItem>()
{
    new SelectListItem{Text="Milk", Value="1"},
    new SelectListItem{Text="coffee", Value="2"},
    new SelectListItem{Text="tea", Value="3"}
};

In your, declare the drop down list:

@Html.DropDownListFor(model => model._drinkType, (IEnumerable<SelectListItem>)ViewBag.DrinkTypeDropDown)

Edit: Since you have the Text property and the selected option will be selected if there is a match in the Value of SelectedListItem, you could add a property in your model:

public string _drinkTypeValue { get; set; }

Before returning the view from the controller action result, you would have to set the _drinkTypeValue based on the value of _drinkType:

model._drinkTypeValue = model._drinkTypeDropDown.Where(item => item.Text == model._drinkType).FirstOrDefault().Value; // You will have to treat null values of FirstOrDefault() here

In your view, bind the drop down value to the _drinkTypeValue:

@Html.DropDownListFor(model => model._drinkTypeValue, Model._drinkTypeDropDown)

When the user submits the form, it will actually submit the _drinkTypeValue so you will have to convert it again to _drinkType in a similar fashion.


Post a Comment for "DropdownListfor To Be Auto Selected On The Basis Of A Value Of String Asp.net Mvc"