如何最好地获得在我的应用程序中工作的下拉列表

时间:2014-10-11 14:23:00

标签: c# asp.net-mvc asp.net-mvc-4 entity-framework-5

我是EntityFramework代码首次迁移的新手,我很难看到如何最好地获取在我的应用程序中运行的下拉列表。我习惯先工作数据库,我会在我的视图模型中放入一个TitleId和一个列表,然后用这个方式绑定下拉列表。

我试图按照以下任务中的建议答案

Best Practices for Lookup Tables in EF Code-First

我得到的问题是视图模型上的标题总是返回将模型提交为null。

请问有人可以提供一些指导吗?

模型

public class CandidateProfile
{
    public ApplicationUser User { get; set; }
    public Title Title { get; set; }
    public string FirstName {get;set;}
}

视图模型

public class PersonalInformationViewModel
{
    [Required]
    [UIHint("TitlePicker")]
    public Title Title {get;set;}
    public string FirstName {get;set;}
}

控制器

public ActionResult RenderHomepage()
{
    var viewModel = new PersonalInformationViewModel();

    ApplicationDbContext context = new ApplicationDbContext();
    ViewBag.Titles = context.Titles.ToList();
    return PartialView("~/Views/Profile/_PersonalInformation.cshtml", viewModel);
}

public ActionResult SubmitPersonalDetails(PersonalInformationViewModel viewModel)
{
    //...
}

视图

    @Html.EditorFor(m => m.Title)

查看/共享/ EditorTemplates

@using Temps.Models
@inherits System.Web.Mvc.WebViewPage<Title>

@Html.DropDownListFor(m => m, new SelectList((IEnumerable<Title>)ViewBag.Titles,
    "Id",
    "Text",
    Model == null ? 1 : Model.Id),
    "-- please select --",
    new { @class = "form-control" })

2 个答案:

答案 0 :(得分:2)

我在过去看到很多问题都是由使用视图包填充下拉引起的。我强烈建议您通过模型传递List。你的下拉应该是这样的

@Html.DropDownListFor(m => m.Title, Model.Titles, "--Please Select--", new { @class = "form-control" }

第一个labda表达式将下拉列表的选定值与模型

联系起来

答案 1 :(得分:1)

Title是一个复杂的对象,但是<select>控制只回发单个值(或多个选择的情况下的数组),因此它不能被绑定。在您的情况下,从<select>发回的值是所选ID的{​​{1}}。 Title尝试将DefaultModelBinder的值设置为(例如)Title,但失败,1为空。

将您的视图模型更改为

Title

由于您已经在使用视图模型,因此最好在此处包含public class PersonalInformationViewModel { [Required] public int? Title {get;set;} public string FirstName {get;set;} public SelectList TitleList { get; set; } } ,而不是使用SelectList。然后在控制器

ViewBag

并在视图中

public ActionResult RenderHomepage()
{
  var viewModel = new PersonalInformationViewModel();
  ApplicationDbContext context = new ApplicationDbContext();
  model.TitleList = new SelectList(context.Titles, "ID", "Text")
  return PartialView("~/Views/Profile/_PersonalInformation.cshtml", viewModel);
}

请注意,似乎没有必要使用@Html.DropDownListFor(m => m.Title, Model.TitleList, "--Please Select--", new { @class = "form-control" } ,在任何情况下EditorTemplate都没有意义。如果Model == null ? 1 : Model.Id),的值为null,则下拉列表将显示Title。如果设置为(比方说)--Please Select--,则会选择1 <option>

在回发后,value="1"的值现在将是所选标题的Title

相关问题