DropDownListFor - 为什么选中的元素总是第一个?

时间:2014-01-20 14:59:50

标签: asp.net-mvc

我的视图中有DropDownListFor

@model UserProfileViewModel

@Html.DropDownListFor(x => x.PreferredLangID,
    new SelectList(Model.PreferredLanguages,
        "LanguageID",
        "DisplayName",
        Model.PreferredLang))

控制器操作:

 public ActionResult EditProfile()
 {
     List<Language> languages = Code.LanguageLogic.GetAllLanguages();
     UserProfile profile = Code.ProfileLogic.GetUserProfile();
     var viewModel = new UserProfileViewModel
     {
         UserID = profile.UserID,
         PreferredLanguages = languages,
         PreferredLang = profile.PreferredLang
     };
     return View(viewModel);
 }

我想,如果我将Model.PreferredLang作为第4个paramater in SelectList's contructor,那么当页面加载时,该元素将在下拉列表中被选中。但是所选元素始终是列表中的第一个元素。

模特:

public class UserProfileViewModel
{
    public Guid UserID { get; set; }
    public Language PreferredLang { get; set; }
    public int PreferredLangID { get; set; }
    public IEnumerable<Language> PreferredLanguages { get; set; }
    //...
}

2 个答案:

答案 0 :(得分:3)

我不知道类型的细节,所以我不能肯定地说,但我猜你可能需要:

@Html.DropDownListFor(x => x.PreferredLangID,
    new SelectList(Model.PreferredLanguages,
        "LanguageID",
        "DisplayName",
        Model.PreferredLang.PreferredLangId))

ETA:

或者,你的补充:

@Html.DropDownListFor(x => x.PreferredLangID,
    new SelectList(Model.PreferredLanguages,
        "LanguageID",
        "DisplayName",
        Model.PreferredLangId))

答案 1 :(得分:0)

对于View的第二个剪辑是正确的:

@Html.DropDownListFor(x => x.PreferredLangID,
new SelectList(Model.PreferredLanguages,
    "LanguageID",
    "DisplayName",
    Model.PreferredLangId))

但是控制器也遗漏了一些东西。还必须设置Model.PreferredLangID

var viewModel = new UserProfileViewModel
{
    UserID = profile.UserID,
    IsAdministrator = profile.IsAdministrator,
    PreferredLanguages = languages,
    PreferredLangID = profile.PreferredLang.LanguageID
};

我不确定,为什么这不适用于

new SelectList(Model.PreferredLanguages,
    "LanguageID",
    "DisplayName",
    Model.PreferredLang.LanguageID))