I would like to set the “selected” option based on my back end data. Here is a sample of my code…
<select id="listName" name="listName">
<option>Select Name</option>
@foreach (var item in ViewBag.NameList as Dictionary<string, string>)
{
//worked in MVC2, not with razor
<option value= '@item.Key' @if (TempData["name"].ToString() == item.Key) { selected = ""selected""); }>@item.Value - @item.Key</option>
string nameSelect = TempData["name"].ToString() == item.Key ? "selected" : "";
<option value= '@item.Key' selected= '@nameSelect'>@item.Value - @item.Key</option>
}
</select>
Is there a better way to do this?
Oh, Hell yeah. Using view models of course. So let’s define a view model:
then a controller action which will populate this view model from your data source:
and finally a corresponding strongly typed view:
Now since you showed some dictionary in your question, we could assume that yo ualready have this dictionary. In your example you’ve stuffed it in ViewBag (which is wrong) but you could bind it to the view model:
That’s ASP.NET MVC: strong typing, view models, no ViewBag.