我的模型在MVC中有问题,该问题在ViewModel到View中传递。我有一个数据库,里面有几个表,我称之为实体框架来创建模型。
这是我的ViewModel:
namespace BP_final.ViewModels
{
public class AllDBModels
{
public Models.Graph AllGraphs { get; set; }
public IEnumerable<NAMTAR_STUDYROOMS> Namtar_studyrooms { get; set; }
public IEnumerable<NAMTAR_STATS_STUDYROOMS> Namtar_stats_studyrooms { get; set; }
public List<bp_data> bp_data { get; set; }
public Models.Report reports { get; set; }
public AllDBModels()
{
Namtar_studyrooms = new List<NAMTAR_STUDYROOMS>();
reports = new Models.Report() { RoomNumber = "1"};
AllGraphs = new Models.Graph();
}
}
}
我为我的表创建了一些属性,并初始化了其中一些。然后在我的控制器中,我调用ViewModel类,这样它就应该创建实例:
public ActionResult Index()
{
AllDBModels allModels = new AllDBModels();
allModels.AllGraphs = new Graph();
allModels.AllGraphs.Charts = new List<Highcharts>();
ChartsModel model = new ChartsModel();
model.Charts = new List<Highcharts>();
...
...
return View(allModels);
在我的视图中,我得到了ViewModel,然后我想使用它。我调用DropDownListFor:
@model BP_final.ViewModels.AllDBModels
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm())
...
...
<div class="form-group">
@Html.LabelFor(model => model.reports.RoomNumber, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10 ">
@Html.DropDownListFor(model => model.reports.RoomNumber, new SelectList(
/*this fails*/ Model.Namtar_studyrooms.Select(x => new SelectListItem{ Value = x.ID.ToString(), Text = x.NAME }), "Value", "Text", 2
), new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.reports.Graph, "", new { @class = "text-danger" })
</div>
</div>
我想用namtar_studyrooms表/模型中的数据填充下拉选项,但不能。它正在为第一个labmda表达式工作,它取自@Html(作为model.reports,而model是我的viewmodel),但我在model中使用的下一个lamda。Namtar_studyroms.Select(不起作用,我在model上得到了null异常。我在互联网上看了看,似乎我和其他人一样拥有一切,我似乎找不到哪里出了问题。
将下拉集合添加到ViewBag。
在控制器中;
public ActionResult Index()
{
AllDBModels allModels = new AllDBModels();
allModels.AllGraphs = new Graph();
allModels.AllGraphs.Charts = new List<Highcharts>();
ChartsModel model = new ChartsModel();
model.Charts = new List<Highcharts>();
ViewBag.Rooms = db.namtar_studyrooms.ToList() //the collection here (you should changeit, just an example)
}
视图中;
@Html.DropDownListFor(model => model.reports.RoomNumber, new SelectList(ViewBag.Rooms, "RoomID", "RoomNameForDisplay"), "Select Room for default", new { @class = "form-control" })
希望有帮助。