2013-07-19 34 views
1

我在這裏做錯了什麼?MVC中的SelectList不正確的語法

我想要做的是將函數值和函數名的列表填充到jSon結果中,然後我將在jQuery的主頁上使用它。

的錯誤是:

錯誤5無法隱式轉換類型 'System.Collections.Generic.IEnumerable' 爲 'System.Web.Mvc.SelectList'。一個顯式轉換存在(是否 缺少強制轉換?)

public ActionResult FilterFunctionList(int departmentID = 0) 
    { 
     if (departmentID == 0) 
     { 
      return this.Json(string.Empty, JsonRequestBehavior.AllowGet); 
     } 
     IPACS_Departments ipacs_department = db.IPACS_Department.Find(departmentID); 
     SelectList ipacs_functions = ipacs_department.IPACS_Functions.Select(m => new SelectListItem 
     { 
      Value = SqlFunctions.StringConvert((double)m.functionID).Trim(), 
      Text = m.name 
     }); 


     return this.Json(ipacs_functions, JsonRequestBehavior.AllowGet); 
    } 
    #endregion 

回答

3

嘗試使用constructor of SelectList that takes an IEnumerable

SelectList ipacs_functions = new SelectList(
    ipacs_department.IPACS_Functions.Select(m => new SelectListItem { 
     Value = SqlFunctions.StringConvert((double)m.functionID).Trim(), 
     Text = m.name 
    }) 
, "Value" 
, "Text" 
); 
+0

這給了我一個錯誤說這個功能只能從LINQ調用實體。並指向})倒數第二行。 –

+0

@JamesWilson'IPACS_Functions'的類型是什麼? – dasblinkenlight

+0

IPACS_Functions的類型爲IPACS_Functions。這是一個自定義實體模型。也許我正在做這個完全錯誤的事情。 IPACS_Functions模型有很多屬性。我所需要的是以json格式返回的每個IPACS_Functions的值/名稱。 –

0

dasblinkenlight當然是正確的,但我更喜歡來定義這些集合爲IEnumberable<SelectListItem>在我的ViewModel代碼後面,以減少必須具有魔術弦「價值」和「文本」參數:

public int FavoriteMovieID { get; set; } 

public IEnumerable<SelectListItem> MoviesToSelectFrom 
{ 
    get 
    { 
     return from x in OrderDetailsRepo.GetAllMovies() 
       select new SelectListItem { 
        Text = x.Title, 
        Value = x.ID.ToString(), 
        Selected = x.id == this.FavoriteMovieID, 
       }; 
    } 
} 

看起來有點清潔,恕我直言。而在觀察側,所有的輔助方法僅僅需要IEnumberable<SelectListItem>,所以他們看起來是一樣的(其選擇列表的工具!):

@Html.DropDownListFor(model => model.FavoriteMovieID, Model.MoviesToSelectFrom)