2014-11-24 73 views
0

我想從表格中得到下拉列表。我有模式:ASPNET MVC中表格的下拉列表

namespace MobileService.Models 
{ 
    public class Mobile 
     { 
      public int Id { get; set; } 

      public string Model { get; set;} 

      Public string EMEI { get; set ;} 

      public int MasterId { get; set; } 

      public List<Master> MasterList { get; set; } 
    } 

    public class Master 
    { 
     public int Id { get; set; } 

     public string Name { get; set; } 
    } 

} 

在控制器我創造了這個模型行動:

public ActionResult Create() 
    { 
     return View(); 
    } 

鑑於:

@model MobileService.Models.Mobile 
@using (Html.BeginForm()) { 

@Html.EditorFor(model => model.Model) 
@Html.EditorFor(model => model.EMEI) 
// And here i want to display a drpodown list with all available masters 

<button type="submit" class="btn btn-primary">Creat</button> 
} 

但它總是告訴我,Model.MasterList爲空。但爲什麼?在模型中,我告訴從另一個模型獲取列表(public List MasterList {get; set;})。爲什麼它是空的?

+4

向我們展示您想要加載模型的控制器代碼.. – Oscar 2014-11-24 20:20:46

+0

[C#MVC從下拉列表中獲取值](https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF -8#q = C%23%20MVC%20get%20values%20 from%20dropdownlist)令人驚訝的是簡單的''GOOGLE SEARCH'可以產出' – MethodMan 2014-11-24 20:22:31

+2

* Model.MasterList爲空。但是爲什麼?* - 你覺得它不會是什麼? – 2014-11-24 20:25:26

回答

0

此代碼在VB中。在開始時,即使我尋找了很多時間,這是我找到的簡單解決方案。

轉換模型到selectListItems名單

Dim lstEmpTypes As New List(Of SelectListItem) 



lstTicketWrTypes.Add(New SelectListItem With {.Text = row("Something"), .Value = row("Something")}) 

'然後將其加載到ViewBag

ViewBag.EmpTypes = lstEmpTypes 

' 而在您查看

    @Html.DropDownList("selectWrType", New SelectList(ViewBag.EmpTypes , "Value", "Text"), New With {.class = "span3"}) 
0

當查詢移動你需要包含(「MasterList」),或者在你的上下文中打開延遲加載(不推薦)

0

對我來說,答案是它添加到控制器:

public ActionResult Create() 
    {  
    ViewBag.MasterId = new SelectList(db.Masters, "Id", "Name"); 
    return View(); 
    } 

然後在視圖來顯示droplist:

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

日Thnx ZIKO誰告訴我現在該名單並沒有加載自然而然。