Reputation: 2791
Consider the following model:
public class TagType
{
public int Id { get; set; }
public string Description { get; set; }
}
public class Tag
{
public int Id { get; set; }
public string Description { get; set; }
public TagType TagType { get; set; }
public DropDownListViewModel TagTypeViewModel { get; set; }
public int TagTypeId { get; set; }
}
I have the following Action in a controller:
public ActionResult Edit(int id)
{
// Load from database
IEnumerable<TagType> tagTypes = TagTypeDal.GetAll().ToList();
Tag tag = TagDal.Get(id);
tag.TagTypeViewModel = new DropDownListViewModel();
tag.TagTypeViewModel.Items = new List<SelectListItem>();
tag.TagTypeViewModel.Items.Add(new SelectListItem { Text = "None", Value = "-1" });
tag.TagTypeViewModel.Items.AddRange(tagTypes
.Select(tt => new SelectListItem
{
Text = tt.Description,
Value = tt.Id.ToString(),
Selected = tt.Id == tag.TagType.Id
}).ToList());
return View(tag);
}
The select list has one element that has Selected=true
, and it's not the first element.
And on my Edit.cshtml I have:
@model Models.Tag
@Html.DropDownListFor(model => model.TagTypeId,
@Model.TagTypeViewModel.Items,
new { @class = "form-control" })
My problem is that the generated drop down never selects the element that has Selected=true
, it always shows the first element.
Am I calling the wrong overload for DropDownListFor
? Or am I building the select list wrong? Or is it somethig else?
Upvotes: 2
Views: 711
Reputation: 12491
You should fill model.TagTypeId
with selected TagTypeId
in your Controller
.
DropDownListFor
selected value depends on first parameter value.
Upvotes: 1