Reputation: 21999
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?
Upvotes: 3
Views: 13872
Reputation:
except @Html.DropDownListFor
, you may code like this:
<option value= '@item.Key' @(TempData["name"].ToString() == item.Key ? "selected" : "")>@item.Value - @item.Key</option>
BTW, I don't like @Html.DropDownListFor ..
Upvotes: 2
Reputation: 1038800
Is there a better way to do this?
Oh, Hell yeah. Using view models of course. So let's define a view model:
public class MyViewModel
{
public string SelectedValue { get; set; }
public IEnumerable<SelectListItem> Values { get; set; }
}
then a controller action which will populate this view model from your data source:
public ActionResult SomeAction()
{
var model = new MyViewModel();
// preselect an item with Value=2
model.SelectedValue = "2";
// this could of course come from a database or something
model.Values = new[]
{
new SelectListItem { Value = "1", Text = "item 1" },
new SelectListItem { Value = "2", Text = "item 2" },
new SelectListItem { Value = "3", Text = "item 3" },
};
return View(model);
}
and finally a corresponding strongly typed view:
@model MyViewModel
....
@Html.DropDownListFor(x => x.SelectedValue, Model.Values, "Select")
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:
public ActionResult SomeAction()
{
Dictionary<string, string> values = ......
var model = new MyViewModel();
model.SelectedValue = (string)TempData["name"];
model.Values = values.Select(x => new SelectListItem
{
Value = x.Key,
Text = string.Format("{0} {1}", x.Key, x.Value)
});
return View(model);
}
That's ASP.NET MVC: strong typing, view models, no ViewBag.
Upvotes: 5