[英]SelectList checkbox
My application is MVC 5, trying to develop multiselect checkbox using the following: 我的应用程序是MVC 5,尝试使用以下方法开发多选复选框:
public static Dictionary<int, string> AdditionalInfo = new Dictionary<int, string>()
{
{ 1, "Exercise" },
{ 2, "Diet" }
};
public static int MapAdditionalInfo (string value)
{
return (from v in AdditionalInfo
where v.Value == value
select v.Key).FirstOrDefault();
}
public static string MapAdditionalInfo (int? value)
{
return (from v in AdditionalInfo
where v.Key == value
select v.Value).FirstOrDefault();
}
public string AdditionalInfo
{
get { return MapAdditionalInfo(AdditionalInfoID); }
set { AdditionalInfoID = MapAdditionalInfo(value); }
}
In the View: 在视图中:
@foreach (SelectListItem item in (IEnumerable<SelectListItem>)ViewData["Info"] )
{
<label><input value="@item.Value" name="AdditionalInfoID" id="AdditionalInfoID" type='checkbox' checked="@item.Selected" class="checkbox-inline" /><span class='lbl padding-4'>@item.Value </span></label>
}
In the controller: 在控制器中:
ViewData["Info"] = MyModel.AdditionalInfo;
I get the following error: 我收到以下错误:
Unable to cast object of type 'System.Collections.Generic.Dictionary`2[System.Int32,System.String]' to type 'System.Collections.Generic.IEnumerable`1[System.Web.Mvc.SelectListItem]'.
Would appreciate your suggestions on how to solve this error or if there a example for a better way to develop a checkbox list. 感谢您对如何解决此错误的建议,或者是否有示例说明开发复选框列表的更好方法。
Just in case someone else has the same problem, here how I solved it: I changed foreach to: 以防万一其他人有相同的问题,这是我如何解决:我将foreach更改为:
@foreach (var item in (Dictionary<int, string>)ViewData["Info"])
The rest of the code above is the same. 上面的其余代码是相同的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.