我能够成功地在插入时将值保存到数据库(标题值),但是当我在编辑模式下呈现相同的 View 时,标题字段必须保存选定的值,但在我的情况下,标题下拉列表没有选择任何值......不知道为什么我得到一个没有选择的下拉列表,而标题字段保存存储的值(在后端)。
@Html.DropDownListFor(model => model.title, new SelectList(Model.titles, "Value", "Text"),"-Select-") // nothing selected on edit mode
@Model.title //displaying the stored value which the user selected initially.
标题值
titles = new SelectList(ListItem.getValues().ToList(), "Value", "Text").ToList();
获取值函数
public static List<TextValue> getValues()
{
List<TextValue> titles= new List<TextValue>();
TextValue T= new TextValue();
T.Value = "Mr";
T.Text = "Mr";
titles.Add(T);
T= new TextValue();
T.Value = "Mrs";
T.Text ="Mrs";
titles.Add(T);
T= new TextValue();
T.Value = "Miss";
T.Text = "Miss";
titles.Add(T);
T= new TextValue();
T.Value ="Other";
T.Text = "Other";
titles.Add(T);
return titles;
}
最佳答案
你必须使用另一个 SelectList ctor
来自 msdn
SelectList(IEnumerable, String, String, Object)
Initializes a new instance of the SelectList class by using the specified items for the list, the data value field, the data text field, and a selected value.
然后 :
@Html.DropDownListFor(model => model.title,
new SelectList(Model.titles, "Value", "Text", Model.title),
"-Select-")
顺便说一句,遵循基本标准通常是个好主意(至少):您的属性应该以大写字符开头。
public string Title {get;set;}
关于asp.net - 在编辑模式下未选择 Html.DropDownListFor 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12927098/