【问题标题】:MVC SelectList postback property not boundMVC SelectList 回发属性未绑定
【发布时间】:2015-04-19 14:41:46
【问题描述】:

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

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

其中vm 是我自己的视图模型,它具有AreaId 作为视图模型中对象之一的属性。

在我的 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 除外。我尝试更改名称以匹配视图模型属性,但我尝试无法让AreaId 显示除 0 以外的任何值。

我的视图模型包括:

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

【问题讨论】:

  • 是否在下拉菜单中显示选项?
  • 是的。只是该值不会在回发时传输。
  • 在您的 @Html.DropDownList 中,您在哪里关联 ViewBag.AreaId 选择列表?
  • 是否可以发布您的整个视图?
  • 你需要展示更多你的观点。您的模型是AnalyserHousesDetailViewModel,但您的方法接受参数AnalyserHouse。为什么你不使用强类型助手来绑定你的属性?如果你有一个视图模型,为什么你有那个糟糕的[Bind] 包含属性并使用ViewBag 属性?如果您有一个名为 AreaId 的属性,那么您需要为选择列表使用不同的名称并使用 @Html.DropDownListFor(m =&gt; m.AnalyserHouse.AreaId, (SelectList)ViewBag.AreaList, new { @class = "form-control" })

标签: c# asp.net-mvc


【解决方案1】:

Stephen 的建议解决了这个问题:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多