我正在生成一个带有预选值的ListBox,如下所示。问题是当我选择其键字符串长度大于1的项目时,列表框选择错误的项目。情况就是这样,
public static System.Web.Mvc.MultiSelectList CreateListBox()
{
List<KeyValuePair<string, string>> alanList = new List<KeyValuePair<string, string>>();
alanList.Add(new KeyValuePair<string, string>("A", "A"));
alanList.Add(new KeyValuePair<string, string>("B", "B"));
alanList.Add(new KeyValuePair<string, string>("BC", "BC"));
alanList.Add(new KeyValuePair<string, string>("C", "C"));
alanList.Add(new KeyValuePair<string, string>("D", "D"));
alanList.Add(new KeyValuePair<string, string>("BAYI", "BAYI"));
List<string> vals = new List<string>();
vals.Add("BAYI");
vals.Add("BC");
System.Web.Mvc.MultiSelectList ret = new System.Web.Mvc.MultiSelectList(alanList, "Key", "Value", vals);
return ret ;
}
在结果中,选择值为A,B和C的HTML项目。未选择BAYI和BC。问题是什么?有什么想法吗?
答案 0 :(得分:4)
以下作品对我很有用,我会向您推荐:
型号:
public class MyViewModel
{
public IEnumerable<string> SelectedItemIds { get; set; }
public IEnumerable<SelectListItem> Items
{
get
{
return new[]
{
new SelectListItem { Value = "A", Text = "A" },
new SelectListItem { Value = "B", Text = "B" },
new SelectListItem { Value = "BC", Text = "BC" },
new SelectListItem { Value = "C", Text = "C" },
new SelectListItem { Value = "D", Text = "D" },
new SelectListItem { Value = "BAYI", Text = "BAYI" },
};
}
}
}
控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
SelectedItemIds = new[] { "BAYI", "BC" }
};
return View(model);
}
}
查看:
@model MyViewModel
@Html.ListBoxFor(
x => x.SelectedItemIds,
new SelectList(Model.Items, "Value", "Text")
)