2012-02-24 26 views
1

我對ASP.NET MVC 2非常陌生,而且我正忙於使用實體模型中的數據填充下拉列表以填充<>。我懷疑我的LINQ可能是錯誤的,但它並沒有傷害找出爲什麼我的代碼不起作用。如何使用實體模型中的數據填充Html.DropDownListFor <>?

我設法預先填充另一個DropDownListFor <>用下面的代碼:

 <div class="editor-field"> 
      <% string[] Days = new string[] { "Monday", "Wednesday", "Friday" };%> 
      <%--<%: Html.DropDownList("Delivery Day", new SelectList(Days)) %>--%> 
      <%: Html.DropDownListFor(model => model.DeliveryDay, new SelectList(Days))%> 
      <%: Html.ValidationMessageFor(model => model.DeliveryDay)%> 
     </div> 

我想現在填充列表如下:

 <div class="editor-field"> 
      <% List<string> categoryList = new List<string>(); 
       var categories = from c in Model.Category select c.Category_Category; 
       foreach (object cata in categories) 
       { 
        categoryList.Add(cata.ToString); 
       }%> 
      <%: Html.DropDownListFor(model => model.Category_Category,new SelectList(categoryList))%> 
      <%: Html.ValidationMessageFor(model => model.Category)%> 
     </div> 

這是發生了什麼:

找不到源類型爲'int?'的查詢模式的實現。 '選擇'未找到。

我該如何解決這個問題?

回答

3
<div class="editor-field"> 
    <% var categories = Model.Category.ToArray().Select(x => new SelectListItem 
     { 
      Value = x.CategoryId.ToString(), 
      Text = x.CategoryName 
     }); 
    %> 
    <%= Html.DropDownListFor(model => model.Category_Category, categories) %> 
    <%= Html.ValidationMessageFor(model => model.Category) %> 
</div> 

這就是說我認爲你錯過了整個MVC模式的重點。你永遠不應該做那樣的事情。一個觀點不應該做這樣的事情。您不應該將您的EF域模型傳遞給您的視圖。您應該使用視圖模型並讓您的控制器操作執行必要的查詢並準備視圖模型。

所以定義視圖模式:

public class MyViewModel 
{ 
    public string SelectedCategoryId { get; set; } 
    public IEnumerable<SelectListItem> Categories { get; set; } 
} 

,然後讓你的控制器動作構建這個視圖模型:

public ActionResult Foo() 
{ 
    var model = new MyViewModel(); 
    model.Categories = db.Category.ToArray().Select(x => new SelectListItem 
    { 
     Value = x.CategoryId.ToString(), 
     Text = x.CategoryName 
    }); 
    return View(model); 
} 

,然後你的觀點會被強類型到MyViewModel,你就可以只需顯示下拉菜單:

<div class="editor-field"> 
    <%= Html.DropDownListFor(x => x.SelectedCategoryId, Model.Categories) %> 
    <%= Html.ValidationMessageFor(x => x.SelectedCategoryId) %> 
</div> 
+0

謝謝。我仍然在學習如何使用MVC。感謝您指出這一點 – Eon 2012-02-24 12:48:57

+0

我會抓這個,並找到另一個點開始 – Eon 2012-02-24 12:50:19

0

將此用於分類IES

<% 
    var categories = (from c in Model.Category select new SelectListItem 
     { 
      Text = c.Category_Category.ToString(), 
      Value = c.Category_Category.ToString() //or I will recommend using the key 
     }).ToList(); 
%>  

然後

<%: Html.DropDownListFor(model => model.Category_Category, categories)%> 

這將是更好地在你的控制器,並具有獨立的視圖模型包含List<SelectListItem>類別屬性視圖來做到這一點。

+0

沒有工作:/ – Eon 2012-02-24 12:47:44

+0

對不起,我已經刪除了'select'關鍵字。 – kingpin 2012-02-24 12:50:08

相關問題