1

What am I doing wrong here?

What I am trying to do is populate a list of Function Value and function Name into a jSon result that I will then use on my main page with jQuery.

The error is:

Error 5 Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'System.Web.Mvc.SelectList'. An explicit conversion exists (are you missing a cast?)

    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
4

2 回答 2

3

尝试使用一个构造函数,SelectList它需要一个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"
);
于 2013-07-19T15:58:38.940 回答
0

dasblinkenlight当然是正确的,但我更喜欢在我的 ViewModel 代码中定义这些集合,IEnumberable<SelectListItem>以减少必须拥有那些神奇的“值”和“文本”参数:

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>(SelectList 实现了!),所以它们看起来是一样的:

@Html.DropDownListFor(model => model.FavoriteMovieID, Model.MoviesToSelectFrom)
于 2013-07-19T19:27:14.113 回答