【发布时间】:2013-05-31 10:22:47
【问题描述】:
我有一个注册表单。我希望用户可以使用 html 中的选择列表来选择他们宠物的种族。所以我决定使用 Html.DropDownListFor() Html helper。
在我的模型中:
public class PetModel
{
public long id { get; set; }
public short gender { get; set; }
public short type { get; set; }
public string name { get; set; }
public int raceID { get; set; }
public int birthYear { get; set; }
public int weight { get; set; }
public bool neutered { get; set; }
public IEnumerable<SelectListItem> raceList { get; set; }
}
我想为raceList填充一个下拉列表,用户可以选择他们宠物的种族。
所以我为局部视图创建了一个控制器
public PartialViewResult _SignupPet(PetModel model)
{
model.raceList = entity.PetRaces.Select(w => new SelectListItem { Text = w.name, Value = w.id.ToString() });
return PartialView(model);
}
在我看来:
@Html.DropDownListFor(m=>m.raceID, Model.raceList)
但是我收到了这个错误。
LINQ to Entities 无法识别方法 'System.String ToString()' 方法,并且这个方法不能翻译成store 表达。
现在我想知道这个。我通常使用下拉列表来选择一个 ID 并向用户显示文本而不是 ID。我将如何在我的项目中使用这个 Html.DropDownListFor() 助手。我是否使用了错误的方法?
【问题讨论】:
-
你能传入 w.name 作为文本和 ID 吗?然后在控制器操作中使用名称?我也遇到过类似的问题,LINQ 无法转换 ToString()。
标签: asp.net-mvc-3 linq asp.net-mvc-4