因此,我的控制器的代码如下:
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>在部分视图中,我正在尝试创建一个名称(我还在学习,这是一个练习应用程序,看看我是否理解了asp.net教程中的概念),然后它将获取这个实体列表,显示一个字段,从另一个字段获取值(“DropDownList”和"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异常,模型为空。索引页面中没有模型,也没有绑定到任何内容,但是,数据是通过ViewBag发送的。
有什么想法吗?
发布于 2012-10-19 15:09:42
您的部分被强类型化为一个模型(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而不是视图模型,因此您需要在partial中继续使用在此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);
}然后将视图和partial强类型化为视图模型:
@model CommunityViewModel
@using (Html.BeginForm("Index","CommunityController"))
{
<div>
@Html.LabelFor(x => x.Id)
@Html.DropDownListFor(x => x.Id, Model.Communities)
</div>
}https://stackoverflow.com/questions/12969014
复制相似问题