2011-02-23 84 views
0

我是MVC的新手,並試圖在我的視圖中使用我的控制器中的「規則」列表填充DropDownList。當我按照列出的方式進行操作時,我只是通過一堆表示CellularAutomata.Models.Rules的項目獲得了一個下拉列表。我知道我這樣做不正確,我只是想知道如何讓它顯示下拉列表中每個規則的規則說明。如何在ASP.NET MVC 3中使用DropDownList

我有一個模型

public class Rule 
{ 
    public int ID { get; set; } 
    public int Name { get; set; } 
    public string Description{ get; set; } 

    public Rule(int name, string description) 
    { 
     Name = name; 
     Description = description; 

    } 
    public Rule() 
    { 
     Name = 0; 
     Description = ""; 
    } 
} 

A控制器

public ActionResult Index() 
    { 
     var rules = from rule in db.Rules 
        select rule; 

     return View(rules.ToList()); 
    } 

和一個視圖

@model IEnumerable<CellularAutomata.Models.Rule> 

@{ 
    ViewBag.Title = "Index"; 
} 
<h2>Index</h2> 

<table> 
    <tr> 
     <td> 
      @Html.DropDownList("Test", new SelectList(Model)) 
     </td> 
    </tr> 
</table> 
+0

@Carnotaurus - 我不知道,如果你想成爲好笑,而是一箇中繼器是一個ASP.NET Web窗體控件。這是MVC。 – Justin 2011-03-14 05:50:25

回答

4

你可以有一個視圖模型:

public class MyViewModel 
{ 
    public string SelectedRuleId { get; set; } 
    public IEnumerable<Rule> Rules { get; set; } 
} 

,然後在你的控制器:

public ActionResult Index() 
{ 
    var model = new MyViewModel 
    { 
     Rules = db.Rules 
    }; 
    return View(model); 
} 

,並在視圖:

@model CellularAutomata.Models.MyViewModel 
@{ 
    ViewBag.Title = "Index"; 
} 
<h2>Index</h2> 

@Html.DropDownListFor(
    x => x.SelectedRuleId, 
    new SelectList(Model.Rules, "ID", "Description") 
) 
+0

因此,如果不使用視圖模型,真的沒有好的方法嗎? – 2011-02-23 20:02:39

+0

@Doug S.,我不知道你對*好方法的定義是什麼,但在ASP.NET MVC中,視圖模型的使用被認爲是最正確的方法。即使這個「Rule」模型也不應該用在視圖模型的視圖和部分中。正確的方法是創建一個適合視圖特定要求的RuleViewModel。然後,您可以使用[AutoMapper](http://automapper.codeplex.com/)在您的模型(推測爲EF)和視圖模型之間進行轉換。 – 2011-02-23 20:08:02

+0

我正在使用EF,當我嘗試實現此答案時,我得到「LINQ to Entities不能識別方法'System.String ToString()'方法,並且此方法不能轉換爲存儲表達式」。我已經做了一些搜索,似乎EF不支持.tostring方法。我似乎無法找到明確的解決方法。在你看來,處理這個錯誤的最好方法是什麼? – 2011-02-23 20:44:59