从两个表中填充单个下拉列表

本文关键字:填充 单个 下拉列表 两个 | 更新日期: 2023-09-27 18:27:39

场景是:

数据存储在项目和邻域表的数据库中。现在,我想用项目id和项目名称以及邻居id和邻居名称填充下拉列表。

我现在通过viewBag发送,如下所示:

ViewBag.NeighbourhoodId = new SelectList(allNeighbourhood(), "Id", "NeighbourhoodName");

在视图页面上,下拉列表填充如下:

@Html.DropDownList("Locations", ViewBag.NeighbourhoodId as SelectList, "Select a location")

现在,如何在此下拉列表中发送另一个viewBag。

第二个问题,我的下拉列表在部分视图中,所以,我将数据发送到部分视图,如下所示:

@Html.Partial("_CommentBoxSection",new Neighbourhood())

如何发送新项目())以及邻居。有没有超负荷的部分,我可以发送他们两个。我看过一些与这个标题有关的帖子,但它们有些不同我最近尝试过这个:

 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我在控制器中没有代码我必须在控制器中传递一些东西吗

从两个表中填充单个下拉列表

不要使用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
        }
    }
}

在您的Razor视图中:

@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")