【问题标题】:Passing a Value from a ViewBag to a partial View将值从 ViewBag 传递到部分视图
【发布时间】:2012-10-09 18:12:59
【问题描述】:

所以我的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 教程中的概念),然后取这个实体列表,显示一个字段,从另一个(“名称”和“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 发送的。

请给点意见?

【问题讨论】:

    标签: asp.net-mvc-4 partial-views viewbag


    【解决方案1】:

    您的部分被强类型化到模型 (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>
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-20
      • 2015-01-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多