2017-10-19 109 views
0

我試圖填充另一個控制器的下拉列表。我有DeviceController有一個@ Html.DropDownList被填充。最初我有在控制器中填充DropDown的代碼。現在我正試圖將它移到指定用於下拉菜單的控制器。所以我有代碼在一個位置填充下拉列表,而不是多個控制器中的相同代碼。下拉正確加載,當我有它在,不過原來的控制器,當我移動它的下拉控制器我收到以下錯誤There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'DropDownDeviceType'.從另一個控制器填充視圖中的下拉列表

我查看代碼 -

@Html.DropDownList("DropDownDeviceType", null, htmlAttributes: new { @class = "form-control" }) 

從我的DropDownController(如果我有這個代碼在我DeviceController它按預期工作)

public void PopulateDevciceType(object selectDeviceType = null) 
    { 
     string voidInd = "N"; 
     var deviceType = db.DeviceTypes 
      .Where(x => x.VoidInd == voidInd) 
      .OrderBy(x => x.DeviceType1); 

     //ViewData["DropDownDeviceType"] = new SelectList(deviceType, "DeviceTypeID", "DeviceType1", selectDeviceType); 
     ViewBag.DropDownDeviceType = new SelectList(deviceType, "DeviceTypeID", "DeviceType1", selectDeviceType); 

    } 

在我DeviceController

//Populate dropdowns 
    DropDownController dropDown = new DropDownController(); 
    dropDown.PopulateDevciceType(model.DeviceTypeID); 

回答

0

我明白你希望將某些任務用於專門課程。但是,我認爲你有點過分想到這一點。

我不是100%確定這個錯誤實際上告訴你的代碼是什麼,但它看起來像你可能有一些不可思議的視圖返回,因爲你在不同的控制器中設置ViewBag信息返回視圖。我是否正確地理解了它的一部分?

不是創建另一個控制器類,而是創建一個處理列表創建和列表創建的靜態函數。當它創建一個列表時,讓它返回。

然後,當你需要一個列表來填充,這樣做的相關負責人方法:

ViewBag.DropDownDeviceType= *wherever-your-static-method-is*.PopulateDeviceType(model.DeviceTypeID); 
相關問題