我无法在下拉列表中设置默认值 [英] I cannot set default value on dropdownlistfor
问题描述
我有一个构造函数,该构造函数传入一个对象的IEnumerable,然后将其从类型为 SelectList 的公共变量中公开.在cshtml文件中,它已映射到DropDownListFor,并且下拉列表填充良好,但是当我尝试将"None selected"附加到下拉列表时,它不会显示在屏幕上,例如
I have a constructor that passes in an IEnumerable of an object and then expose it from a public variable of type SelectList. In the cshtml file It has been mapped to a DropDownListFor and the dropdown populates fine, However when I try to attach "None selected" to the dropdown it doesn't display in the screen e.g.
视图模型的构造函数:
IEnumerable<Partner> beneficiaryNames
在构造函数中设置值:
BeneficiaryNames = new SelectList(beneficiaryNames, "Id", "Name");
viewmodel中的声明:
declaration in viewmodel:
public SelectList BeneficiaryNames { get; set; }
然后在我看来:
@Html.DropDownListFor(m => m.SearchRequest.BeneficiaryId, Model.BeneficiaryNames, "None selected")
推荐答案
在视图模型的构造函数中,我不得不将一个新对象强制放入列表中.因此我不得不用 List< Partner>替换
BeneficiaryNames = new SelectList(beneficiaryNames,"Id","Name");
newList = new List< Partner>(){新伙伴{ID = 0,名称=未选择"}};newList.AddRange(受益人名称);BeneficiaryNames = new SelectList(newList,"Id","Name");
in the constructor of the view model I had to force a new object into the list. so I had to replace BeneficiaryNames = new SelectList(beneficiaryNames, "Id", "Name");
with List<Partner> newList = new List<Partner>() { new Partner { Id = 0, Name = "None Selected" } };
newList.AddRange(beneficiaryNames);
BeneficiaryNames = new SelectList(newList, "Id", "Name");
这篇关于我无法在下拉列表中设置默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!