场景是:
数据存储在项目和邻居表中的数据库中。 现在,我想用项目ID和项目名称以及neighbourhoodId和邻居名称填充下拉列表。
我现在通过viewBag这样发送:
ViewBag.NeighbourhoodId = new SelectList(allNeighbourhood(), "Id", "NeighbourhoodName");
在视图页面上,获取下拉列表如下:
@Html.DropDownList("Locations", ViewBag.NeighbourhoodId as SelectList, "Select a location")
现在,如何在此dropdownList中发送另一个viewBag。
第二个问题,我的下拉列表是部分视图因此,我将数据发送到这样的部分视图:
@Html.Partial("_CommentBoxSection",new Neighbourhood())
如何与邻居一起发送新的Project())。我可以发送它们的部分重载吗? 我看过一些与这个标题相关的帖子,但它们有所不同 我最近试过这个:
public class ProjectAndNeighbourhoodListItemViewModel
{
public Project Project { get; set; }
public Neighbourhood Neighbourhood { get; set; }
public string ProjectName { get; set; }
public int Id { get; set; }
public bool IsSelected { get; set; }
// public IEnumerable<SelectListItem> ToSelectListItem { get; set; }
public SelectListItem ToSelectListItem()
{
return new SelectListItem
{
Text = Project.ProjectName,
Value = Neighbourhood.Id.ToString(),
Selected = IsSelected
};
}
}
直接在视图页面上
@model @model IEnumerable<ProjectAndNeighbourhoodListItemViewModel>
@Html.DropDownList("Locations", Model.Select(m => m.ToSelectListItem()), "Select a location")
但是获取System.ArgumentNullException值不能为null我在控制器中没有代码我是否必须在控制器中传递一些东西
答案 0 :(得分:0)
不要使用ViewBag将值传递给视图,而是使用ViewModels,它更清晰。 ViewModel也是创建SelectListItems的好地方。在控制器中创建或映射ViewModel。
// ViewModel for a single selectable entry
public class ProjectAndNeighbourhoodListItemViewModel {
public string ProjectName { get; set; }
public long NeighbourhoodId { get; set; }
public bool IsSelected { get; set; }
public SelectListItem ToSelectListItem() {
return new SelectListItem {
Text = ProjectName,
Value = NeighbourhoodId.ToString(),
Selected = IsSelected
}
}
}
在你的剃刀视图中:
@model IEnumerable<ProjectAndNeighbourhoodListItemViewModel>
@* Would be even better to use a wrapper model that contains the collection of list items as property! *@
@Html.DropDownList("Locations", Model.Select(m => m.ToSelectListItem()) , "Select a location")