将@ Html.DropDownList与ViewModel一起使用

时间:2014-04-24 10:05:18

标签: asp.net asp.net-mvc viewmodel html.dropdownlistfor

我有一个viewmodel如下:

public class WhItemForm
{
    public virtual WhItem WhItem { get; set; }
    public virtual WhItemStock WhItemStock { get; set; }
}

在我的控制器中,我使用ViewBag填写选择列表,如下所示:

public ActionResult Create()
    {
        ViewBag.WhBrandId = new SelectList(db.WhBrand, "Id", "Name");
        ViewBag.WhStockCardId = new SelectList(db.WhStockCard, "Id", "Name");
        ViewBag.WhLocationId = new SelectList(db.WhLocation, "Id", "Name");
        return View();
    }

我的WHITEM模型中有BrandID属性,这是我的WHITEM模型。

public class WhItem
{
    public int Id { get; set; }

    public int WhBrandId { get; set; }
    public virtual WhBrand WhBrand { get; set; }

}

当我从视图发布数据时,我无法设置WhBrandID,我的观点如下:

 <div class="form-group">
            @Html.LabelFor(model => model.WhItem.WhBrandId, "WhBrandId", new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("WhBrandId", String.Empty)
                @Html.ValidationMessageFor(model => model.WhItem.WhBrandId)
            </div>
        </div>

我知道,我需要将此值作为WhItem.WhBrandId传递,因为我在视图中使用了viewmodel。我可以为@html.TextBoxFor执行此操作但是如何更正我的下拉列表以将其值作为WhItem.WhBrandId传递给控制器​​。

问候

1 个答案:

答案 0 :(得分:4)

首先我建议您像这样编辑控制器:

    public ActionResult Create()
    {
        ViewBag.SelectList = new List<SelectListItem>
        {
            new SelectListItem{Text = "Text",Value = "Value"},
            new SelectListItem{Text = "Text",Value = "Value"},
            new SelectListItem{Text = "Text",Value = "Value"}
        };

        return View();
    }

之后编辑您的视图:

@Html.DropDownListFor(x => x.WhItem.WhBrandId, (List<SelectListItem>)ViewBag.SelectList)