MVC SelectList回发属性未绑定

时间:2015-04-18 21:44:18

标签: c# asp.net-mvc

我有一个在我的控制器中创建的选择列表,如下所示:

ViewBag.AreaId = new SelectList(
    db.Areas.Where(a => a.ProjectId == vm.Project.ProjectId), 
    "AreaId", 
    "", 
    analyserHouse.AreaId);

其中vm是我自己的viewmodel,它具有AreaId作为viewmodel中某个对象的属性。

在我的create.cshtml中按照MVC默认值插入选择列表:

@Html.DropDownList(
    "AreaId", 
    null, 
    htmlAttributes: new { @class = "form-control" })

控制器方法:

public async Task<ActionResult> Create(
    string reference, 
    [Bind(Include = "AreaId,
                     Name,
                     AnalyserHouseType,
                     Length,
                     Width,
                     Height,
                     WallThickness,
                     RoofThickness,
                     FloorThickness,
                     AreaClassificationInside,
                     AreaClassificationOutside,
                     FireRating,
                     FireRatingDoors")] AnalyserHouse analyserHouse)

AnalyserHouse是一个实体,除AreaId外,所有属性都被正确绑定。我尝试更改名称以匹配viewmodel属性,但我尝试我不能让AreaId显示除0以外的任何值。

我的viewmodel包含:

public class AnalyserHousesDetailViewModel : SidcBaseViewModel
{
    public AnalyserHouse AnalyserHouse { get; set; }
}

1 个答案:

答案 0 :(得分:0)

斯蒂芬的建议解决了这个问题:

@Html.DropDownListFor(m => m.AnalyserHouse.AreaId, (SelectList)ViewBag.AreaList, new { @class = "form-control" })