首先我使用的是MVC 2.0。我在回发到控制器时使用Multiselect列表框进行选择时遇到问题。这是我的代码:
模型
public class TestModel
{
public MultiSelectList AvailableTestTypes { get; set; }
public List<TestType> SelectedTestTypes { get; set; }
}
public class TestType
{
public long Id { get; set; }
public string Name { get; set; }
public bool isActive { get; set; }
}
控制器
public ActionResult Index(TestModel model)
{
if (model == null) model = new TestModel();
List<TestType> testList = new List<TestType>()
{
new TestType() { Id = 1, Name = "TESTING", isActive = true },
new TestType() { Id = 2, Name = "TESTING2", isActive = true },
new TestType() { Id = 3, Name = "TESTING3", isActive = true }
};
model.AvailableTestTypes = testList; //TODO: Fetch From Repository
return View(model);
}
[HttpPost]
public ActionResult PostForm(TestModel model)
{
List<long> act = model.SelectedTestTypes != null ? model.SelectedTestTypes.Select(x => x.Id).ToList() : new List<long>();
查看
<%= Model != null && Model.AvailableTestTypes != null ?
Html.ListBoxFor(x => x.SelectedTestTypes,
new MultiSelectList(Model.AvailableTestTypes, "Id", "Name", Model.SelectedTestTypes),
new { @id = "testListboxId", @class = "blah", @title = "title" }) : null%>
在发布到控制器之后,无论我选择了多少,我的选择列表数都是0 ... 我在这里弄错了什么?
我尝试了一些不同的解决方案,比如 Challenges with selecting values in ListBoxFor 但没有任何效果:(
答案 0 :(得分:1)
您的脚本与另一个脚本中的示例之间的区别在于您尝试绑定到List而不是int []。
如果要填充多选列表框,则必须设置DataValueField和DataTextfield,否则不设置任何值。
model.AvailableTestTypes = new MultiSelectList(testList, "Id", "Name);
然后尝试使用这个类:
public class TestModel
{
public MultiSelectList AvailableTestTypes { get; set; }
public int[] SelectedTestTypes { get; set; }
}
在PostForm操作中,您可以使用ID来检索TestTypes。