asp.net - 在编辑模式下未选择 Html.DropDownListFor 值

标签 asp.net asp.net-mvc asp.net-mvc-3 html.dropdownlistfor

我能够成功地在插入时将值保存到数据库(标题值),但是当我在编辑模式下呈现相同的 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/

相关文章:

C#MVC : Cannot Debug in IIS Express

asp.net-mvc-3 - 如何在MVC route 组合CatchAll和EndsWith?

asp.net-mvc-3 - MVC 3、单选按钮和模型

c# - 在 C# 中为 HMAC SHA1 生成公钥和 secret

c# - 在客户端没有回发的主从 DropDownLists

c# - 枚举显示名称 : Templates can be used only with field access

asp.net - Web.Config - 由于权限不足无法读取配置文件

asp.net-mvc - asp.net mvc 从搜索引擎抓取中排除一个 Action

c# - ASP.NET WebForms WebSite - 控件在代码隐藏中而不是在前端更改它们的值

asp.net - 为网站的私有(private)测试版添加安全层的最不显眼的方法是什么?