0

所以我的Controller的代码如下:

private CommunityModelsContext dbCommunities = new CommunityModelsContext();

// GET: /Home/
public ActionResult Index()
{
     //retrieve the Communities 
     ViewBag.Communities = dbCommunities.Communities.ToList();
     return View();
}

我的视图有这条重要的线来启动部分视图

<div id="LeftView" class="PartialView">@{Html.RenderPartial("CommunitiesPartial");}</div>

在部分视图中,我正在尝试创建一个 DropDownList (我还在学习,这是一个练习应用程序,只是为了看看我是否理解了 asp.net 教程中的概念),然后将使用这个 List实体,显示一个字段,从另一个获取值(“名称”和“id”)

@model BuildingManagement.Models.Community.Community

@Html.BeginForm("Index","CommunityController")
{
    <div>
        @Html.LabelFor(x => x.Name)
        @Html.DropDownList("Community" , new SelectList(Model.Name,"id","Name"))
    </div>
}

现在这会引发 NullReference 异常,模型为空。Index 页面中没有模型,也没有绑定到任何东西,但是,数据是通过 ViewBag 发送的。

请问有什么想法吗?

4

1 回答 1

3

您的部分被强类型化为模型 ( BuildingManagement.Models.Community.Community)。所以你需要先把这个模型传给主视图:

public ActionResult Index()
{
    //retrieve the Communities 
    ViewBag.Communities = dbCommunities.Communities.ToList();
    BuildingManagement.Models.Community.Community model = ... retrieve your model
    return View(model);
}

然后由于您决定使用 ViewBag 而不是视图模型,因此您需要继续使用您在局部视图中定义的值:

@Html.DropDownList("Community", new SelectList(ViewBag.Communities, "id", "Name"))

当然,更好的方法是使用视图模型:

public class CommunityViewModel
{
    [DisplayName("Name")]
    public int Id { get; set; }
    public IEnumerable<SelectListItem> Communities { get; set; }
}

然后让您的控制器填充视图模型并将此视图模型传递给视图:

public ActionResult Index()
{
    //retrieve the Communities 
    var communities = dbCommunities.Communities.ToList().Select(x => new SelectListItem
    {
        Value = x.Id.ToString(), 
        Text = x.Name
    })
    var model = new CommunityViewModel
    {
        Communities = communities
    }
    return View(model);
}

然后将您的视图和部分强类型化为视图模型:

@model CommunityViewModel
@using (Html.BeginForm("Index","CommunityController"))
{
    <div>
        @Html.LabelFor(x => x.Id)
        @Html.DropDownListFor(x => x.Id, Model.Communities)
    </div>
}
于 2012-10-19T07:09:42.413 回答