DropDownList MVC返回null

时间:2014-12-17 16:59:20

标签: asp.net-mvc drop-down-menu

我最近在ASP.NET MVC中使用DropDownList遇到了一些问题。 我想将所选项目的价值保存到名为Wydzialy的成员。 很抱歉没有翻译某些名字,我认为它们并不重要:)

这就是我所拥有的:

查看:

<div class="form-group">
    @Html.LabelFor(model => model.Wydzial, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownListFor(x => x.Wydzial, (List<SelectListItem>)ViewBag.Wydzialy)
    </div>
</div>

型号:

public class Student
{
    public int Id { get; set; }
    public int NumerIndeksu { get; set; }
    public string Imie { get; set; }
    public string Nazwisko { get; set; }
    public int Semestr { get; set; }
    public virtual Wydzial Wydzial { get; set; }
}

控制器:

 public ActionResult Create()
    {
        var wydzialy = db.Wydzialy.ToList();
        var lista = wydzialy.Select(W => new SelectListItem()
            {
                Text = W.Nazwa
            }).ToList();
        ViewBag.Wydzialy = lista;
        return View();
    }

1 个答案:

答案 0 :(得分:0)

您尝试将下拉列表绑定到复杂对象。 <Select>仅发布一个值类型(在您的情况下是所选选项的文本)。

绑定到Wydzial

的属性
@Html.DropDownListFor(x => x.Wydzial.Nazwa, (List<SelectListItem>)ViewBag.Wydzialy)

或者最好使用包含要绑定的属性和SelectList

的视图模型
public class StudentVM
{
  public int Id { get; set; }
  // Other properties used by the view
  public string Wydzial { get; set; }
  public SelectList Wydzialy { get; set; }
}

控制器

public ActionResult Create()
{
  StudentVM model = new StudentVM();
  model.Wydzialy = new SelectList(db.Wydzialy, "Nazwa", "Nazwa")
  return View(model );
}

查看

@model StudentVM
....
@Html.DropDownListFor(x => x.Wydzial, Model.Wydzialy)

请注意,您似乎只绑定Nazwa的{​​{1}}属性。通常,您将显示文本属性,但绑定到ID属性。

相关问题