您好我在index.cshtml页面中使用局部视图。部分视图包含一个从数据库动态绑定的下拉列表。
我不想使用viewbag或viewdata来绑定此下拉列表。
在控制器
中 // GET: Reporting/Home
public ActionResult Index()
{
var view = View();
return view;
}
public ActionResult _ReportingMenu()
{
var DashboardList = GetAllDashboards();
return View(DashboardList);
}
public IEnumerable<DashboardDefinition> GetAllDashboards()
{
return _reortDefinitionService.GetAllDashboards();
}
在index.cshtml中
@model IEnumerable<Portal.Domain.ReportingModule.ReportDefinition.DashboardDefinition>
@{
ViewBag.Title = "Reporting";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Reporting View</h2>
@Html.ActionLink("Add new Chart", "Create", "Chart", new { area = "Reporting" }, null)
@Html.Partial("_ReportingMenu")
在Partialview中
@model Portal.Domain.ReportingModule.ReportDefinition.DashboardDefinition
<div class="nav navbar navbar-default navbar-no-margin submenu">
@Html.DropDownList("Mobiledropdown1",IEnumerable<Model.DashboardName>)
<a id="SubMenuIntegratorNew" class="btn btn-default submenu-item" href="#">
<i class="fa fa-file-o fa-lg"></i>
<span class="submenu-item-text">New</span>
</a>
<a id="SubMenuIntegratorSave" class="btn btn-default submenu-item" href="#">
<i class="fa fa-floppy-o fa-lg"></i>
<span class="submenu-item-text">Save</span>
</a>
<a id="SubMenuIntegratorSaveAs" class="btn btn-default submenu-item" href="#">
<i class="fa fa-files-o fa-lg"></i>
<span class="submenu-item-text">Save As</span>
</a>
<a id="SubMenuIntegratorAddChart" class="btn btn-default submenu-item" href="#">
<i class="fa fa-picture-o fa-lg"></i>
<span class="submenu-item-text">Add Chart</span>
</a>
</div>
但是我得到了null模型的错误。
我不知道如何在局部视图中实现
答案 0 :(得分:4)
您应该使用视图模型,因此您可以同时包含列表和所选属性,例如:
public class DashboardViewModel
{
public IEnumerable<SelectListItem> Data { get; set; }
//Might not be an int, but just an example
public int SelectedId { get; set; }
}
然后在控制器中填充它:
public ActionResult _ReportingMenu()
{
var DashboardList = GetAllDashboards();
var dropdownData = DashboardList
.Select(d => new SelectListItem
{
Text = d.Name, //Need to apply the correct text field here
Value = d.Id.ToString() //Need to apply the correct value field here
})
.ToList();
var model = new DashboardViewModel
{
Data = dropdownData
};
return View(model);
}
然后在您的两个视图中,设置模型:
@model DashboardViewModel
然后在你的部分你可以做:
@Html.DropDownListFor(m => m.SelectedId, Model.Data)