2016-05-12 15 views
-1

我在MVC中有問題,我的模型是在ViewModel中傳遞給View的。我有幾個表的數據庫,我稱之爲實體框架來創建模型。MVC當我想通過Model訪問模型時,在ViewModel中傳遞的Model上的Null異常。不是@Html

這是我的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); 

在我看來,我得到的視圖模型,然後我想用它。我叫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),但下一個lamda與Model.Namtar_studyrooms.Select一起使用(不起作用,我在Model上得到了null異常。我看着在互聯網上,似乎我的一切其他人一樣,我似乎無法找出什麼是錯的

+0

去看看這個...... http://stackoverflow.com/a/33327821/3777098 – alikuli

+0

你已經顯示的代碼不會拋出該錯誤,雖然yu顯示沒有任何意義,因爲「Namtar_studyrooms」是一個空列表並且不會顯示任何選項。並且在'SelectList'構造函數中添加最後一個參數('2')是毫無意義的(因爲它的'reports.RoomNumber'的值決定了選擇的內容,所以忽略它。 –

回答

0

添加下拉集合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) 
} 

在View ;

@Html.DropDownListFor(model => model.reports.RoomNumber, new SelectList(ViewBag.Rooms, "RoomID", "RoomNameForDisplay"), "Select Room for default", new { @class = "form-control" }) 

希望有助於。

相關問題