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

Ank*_*kit 5 asp.net asp.net-mvc html.dropdownlistfor asp.net-mvc-3

我可以在插入时成功将值保存到数据库(标题值),但是当我在编辑模式下渲染同一视图时,标题字段必须保存所选值,但是在我的情况下,标题下拉列表没有选择任何值...不知道为什么我在标题字段保留存储的值(在后端)时没有选择任何内容的下拉菜单。

@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.
Run Code Online (Sandbox Code Playgroud)


标题值

titles = new SelectList(ListItem.getValues().ToList(), "Value", "Text").ToList();
Run Code Online (Sandbox Code Playgroud)

getValue函数

 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;

   }
Run Code Online (Sandbox Code Playgroud)

Rap*_*aus 3

你必须使用 SelectList 的另一个成员

来自msdn

SelectList(IEnumerable, String, String, Object) 
Run Code Online (Sandbox Code Playgroud)

使用列表的指定项、数据值字段、数据文本字段和选定的值初始化 SelectList 类的新实例。

然后 :

@Html.DropDownListFor(model => model.title, 
                      new SelectList(Model.titles, "Value", "Text", Model.title),
                      "-Select-") 
Run Code Online (Sandbox Code Playgroud)

顺便说一句,遵循基本标准(至少)通常是一个好主意:您的属性应该以大写字符开头。

public string Title {get;set;}
Run Code Online (Sandbox Code Playgroud)