[英]ASP.NET MVC DropDownList not setting selected value
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.选择列表有一个具有
Selected=true
元素,它不是第一个元素。 And on my Edit.cshtml I have:在我的 Edit.cshtml 上,我有:
@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.我的问题是生成的下拉列表永远不会选择具有
Selected=true
的元素,它总是显示第一个元素。
Am I calling the wrong overload for DropDownListFor
?我是否为
DropDownListFor
调用了错误的重载? Or am I building the select list wrong?还是我构建的选择列表错误? Or is it somethig else?
或者是别的什么?
You should fill model.TagTypeId
with selected TagTypeId
in your Controller
.您应该在
Controller
使用选定的TagTypeId
填充model.TagTypeId
。
DropDownListFor
selected value depends on first parameter value. DropDownListFor
选择的值取决于第一个参数值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.