gpt4 book ai didi

asp.net-mvc - MVC3 View中的CheckboxList,获取传递给 Controller ​​的选中项

转载 作者:行者123 更新时间:2023-12-03 10:32:40 26 4
gpt4 key购买 nike

我有一个关于 MoreInfo 的类(class):

public class MoreInfo
{
public string Name { get; set; }
public string selectedCheckboxItems {get; set;}
}

我想知道如何在 View 上创建一个复选框列表,并在提交时将选中的项目传递给我的 Controller 。

我将如何创建复选框列表以及如何传递所有选中的项目并处理它们?

最佳答案

让我们稍微修改一下您的模型:

public class ItemViewModel
{
public string Id { get; set; }
public string Name { get; set; }
public bool Checked { get; set; }
}

那么你可以有一个 Controller :
public class HomeController: Controller
{
public ActionResult Index()
{
// This action is used to render the form =>
// we should populate our model with some values
// which could obviously come from some data source
var model = new[]
{
new ItemViewModel { Id = "1", Checked = true, Name = "item 1" },
new ItemViewModel { Id = "2", Checked = false, Name = "item 2" },
new ItemViewModel { Id = "3", Checked = true, Name = "item 3" },
};
return View(model);
}

[HttpPost]
public ActionResult Index(IEnumerable<ItemViewModel> items)
{
// This action will be invoked when the form is submitted
// and here the view model will be properly bound and
// you will get a collection of all items with their
// corresponding id, name and whether they were checked or not
...
}
}

那么您将有一个相应的 View ( ~/Views/Home/Index.cshtml ),其中包含允许用户选中/取消选中值的表单:
@model IEnumerable<AppName.Models.ItemViewModel>
@using (Html.BeginForm())
{
@Html.EditorForModel()
<input type="submit" value="OK" />
}

最后是编辑器模板( ~/Views/Home/EditorTemplates/ItemViewModel.cshtml ):
@model AppName.Models.ItemViewModel
// Those two hidden fields are just to persist the id and name
@Html.HiddenFor(x => x.Id)
@Html.HiddenFor(x => x.Name)
<div>
@Html.CheckBoxFor(x => x.Checked)
@Html.LabelFor(x => x.Checked, Model.Name)
</div>

关于asp.net-mvc - MVC3 View中的CheckboxList,获取传递给 Controller ​​的选中项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5284395/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com