从“视图中的下拉列表”中选择并传回Controller

时间:2013-12-20 10:25:45

标签: asp.net-mvc

我有一个这样的模型:

public class UserProfile
{
    public Guid ID { get; set; }
    public string DisplayName { get; set; }
    public Language PreferredLang { get; set; }
}
public class Language
{
    [Key]
    public int LanguageID { get; set; }
    public string LanguageCode { get; set; }
    public string DisplayName { get; set; }
}

我希望能够从下拉列表中选择首选语言。

在控制器中,我获取语言列表并将其放入ViewBag中。在视图中我加载此列表。然后我想保存选择。

我的控制器:

public ActionResult EditProfile()
{
    List<Language> langauges =  Logic.GetAllLanguages();
    ViewBag.Languages = langauges;
    UserProfile profile = GetUserProfile();
    return View(profile);
}

我的观点:

@using (Html.BeginForm()) {

    @Html.EditorFor(model => model.DisplayName)
    <div class="display-field">
        @Html.DropDownListFor(x => x.PreferredLang, new SelectList(ViewBag.Languages, "LanguageID", "DisplayName") as SelectList)

    </div>
    <input type="submit" value="Save" />
}

当用户点击“保存”时,传递给控制器​​的element对象有DisplayName,但PreferredLang始终为空。 如何将语言传回控制器?

[HttpPost]
public ActionResult EditProfile(UserProfile element)
{
    //save element
}

1 个答案:

答案 0 :(得分:3)

创建具有以下属性的ViewModel:

  

UserProfileViewModel

public class UserProfileViewModel
{
    public Guid ID { get; set; }
    public string DisplayName { get; set; }
    public int PreferredLangID { get; set; }
    public IEnumerable<Language> PreferredLanguages { get; set; }
}
  

查看

@using (Html.BeginForm())
{
    @Html.HiddenFor(model => model.ID)
    @Html.EditorFor(model => model.DisplayName)
    <div class="display-field">
        @Html.DropDownListFor(x => x.PreferredLangID, new SelectList(Model.PreferredLanguages, "LanguageID", "DisplayName"))
    </div>
    <input type="submit" value="Save" />
}
  

控制器

public ActionResult EditProfile()
{
    List<Language> languages = Logic.GetAllLanguages();
    UserProfile profile = GetUserProfile();
    var viewModel = new UserProfileViewModel
        {
            ID = profile.ID,
            DisplayName = profile.DisplayName,
            PreferredLanguages = languages
        };
    return View(viewModel);
}

[HttpPost]
public ActionResult EditProfile(UserProfileViewModel viewModel)
{
    List<Language> languages = Logic.GetAllLanguages();
    if(ModelState.IsValid)
    {
        var userProfile = new UserProfile
            {
                ID = viewModel.ID,
                DisplayName = viewModel.DisplayName,
                PreferredLang = languages.FirstOrDefault(l => l.LanguageID == viewModel.PreferredLangID)
            };
        //save element
    }
    viewModel.PreferredLanguages = languages;
    return View(viewModel);
}