C# 当我想通过模型访问模型时,在ViewModel中传递给View的模型上的MVC Null异常。不是@Html
在MVC中,我的模型在ViewModel中传递给View时遇到问题。我的数据库中有几个表,我在这些表上调用实体框架来创建模型 这是我的ViewModel:C# 当我想通过模型访问模型时,在ViewModel中传递给View的模型上的MVC Null异常。不是@Html,c#,asp.net,asp.net-mvc,viewmodel,C#,Asp.net,Asp.net Mvc,Viewmodel,在MVC中,我的模型在ViewModel中传递给View时遇到问题。我的数据库中有几个表,我在这些表上调用实体框架来创建模型 这是我的ViewModel: namespace BP_final.ViewModels { public class AllDBModels { public Models.Graph AllGraphs { get; set; } public IEnumerable<NAMTAR_STUDYROOMS>
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表/模型中的数据填充下拉选项,但无法。它适用于从@Html获取的第一个labmda表达式作为model.reports,而model是我的viewmodel,但我与model.Namtar_studyrooms.Select一起使用的下一个lamda不起作用,并且我在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)
}
希望有帮助。去看看这个。。。您显示的代码不会抛出该错误,尽管您显示的内容没有意义,因为Namtar_studyrooms是一个空列表,不会显示任何选项。在SelectList构造函数中添加最后一个参数2是没有意义的,它被忽略了,因为它是reports.RoomNumber的值,它决定了所选择的内容。
@Html.DropDownListFor(model => model.reports.RoomNumber, new SelectList(ViewBag.Rooms, "RoomID", "RoomNameForDisplay"), "Select Room for default", new { @class = "form-control" })