我是 MVC3 的新手,我不知道如何在 MVC 中使用复选框。
我有一堆文字在我看来
text1
text2
text3
text4
text5
submitbutton
此文本与任何模型无关,它只是纯文本。我想为每个项目放置一个复选框并将其链接到 Controller ,以便当用户选择某些复选框值并单击提交按钮时,我的 Controller 会选择已选择的项目。
我尝试使用 @html.checkbox("text"+ index) 并尝试将 Controller 设为
[HttpPost]
public ActionResult controller(List<string> list)
{
}
但这并没有选择所选项目的列表。你能告诉我我做错了什么或其他方法吗?
最佳答案
使用您的所有值创建一个 ViewModel。填充 ViewModel 并将其发送到 View 。当检查某些内容时,您就会知道帖子中的内容。
public class MyModelViewModel
{
public List<CheckBoxes> CheckBoxList {get; set;}
// etc
}
public class CheckBoxes
{
public string Text {get; set;}
public bool Checked {get; set;}
}
[HttpPost]
public ActionResult controller(MyModelViewModel model)
{
foreach(var item in model.CheckBoxList)
{
if(item.Checked)
{
// do something with item.Text
}
}
}
基本上 ViewModels 是你的 friend 。您希望每个 View 都有一个单独的 View 模型,它是在 Controller 和 View 之间来回传递的。然后,您可以在 Controller 中或(最好)在服务层中进行数据解析。
附加引用:
Should ViewModels be used in every single View using MVC?
关于asp.net-mvc - MVC3 - 如何正确使用@html.checkbox?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9864801/