部分视图传viewbag_从ViewBag传递一个值到一个局部视图

So my Controller's code is as follows:

private CommunityModelsContext dbCommunities = new CommunityModelsContext();

// GET: /Home/

public ActionResult Index()

{

//retrieve the Communities

ViewBag.Communities = dbCommunities.Communities.ToList();

return View();

}

And my View has this all important line to start the Partial View

@{Html.RenderPartial("CommunitiesPartial");}

and in the Partial view, I'm trying to create a DropDownList (I'm still learning, this is a practice app just to see if I've understood the concepts from the asp.net tutorial), that will then take this List of entities, display one field, gets the value from the Other ("Name" and "id")

@model BuildingManagement.Models.Community.Community

@Html.BeginForm("Index","CommunityController")

{

@Html.LabelFor(x => x.Name)

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

}

Now this throws a NullReference Exception, the model is null. There is no model in the Index page and it is not bound to anything, however, the data is being sent through the ViewBag.

Ideas please?

解决方案

Your partial is strongly typed to a model (BuildingManagement.Models.Community.Community). So you need to pass this model to the main view first:

public ActionResult Index()

{

//retrieve the Communities

ViewBag.Communities = dbCommunities.Communities.ToList();

BuildingManagement.Models.Community.Community model = ... retrieve your model

return View(model);

}

and then since you decided to use ViewBag instead of view models you need to keep using the value you defined in this ViewBag inside your partial:

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

Of course a much better approach is to use a view model:

public class CommunityViewModel

{

[DisplayName("Name")]

public int Id { get; set; }

public IEnumerable Communities { get; set; }

}

and then have your controller populate the view model and pass this view model to the view:

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);

}

and then make your view and partial strongly typed to the view model:

@model CommunityViewModel

@using (Html.BeginForm("Index","CommunityController"))

{

@Html.LabelFor(x => x.Id)

@Html.DropDownListFor(x => x.Id, Model.Communities)

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值