gpt4 book ai didi

c# - 复选框和模型绑定(bind)的动态列表

转载 作者:可可西里 更新时间:2023-11-01 08:21:39 25 4
gpt4 key购买 nike

我正在尝试创建一个 View ,其中包含一个从数据库动态创建的复选框列表,然后在回发表单时检索所选复选框的列表。

我的 EF 模型包含一个类:

public class ItemIWouldLikeACheckboxFor {
public int Id { get; set; }
public string Description { get; set; }
}

我有一个包含以下列表的 View 模型:

public class PageViewModel {
// various other properties
public List<ItemIWouldLikeACheckboxFor> checkboxList { get; set; }
}

我的 Controller 获取方法:

public ActionResult Create() {
var viewModel = new PageViewModel();
viewModel.checkboxList = db.ItemIWouldLikeACheckboxFors.ToList();
return View(viewModel);
}

我的看法:

<% using (Html.BeginForm()) { %>
<%-- other stuff here... %>

<% foreach (var item in checkboxList) { %>
<%: Html.CheckBox( <!-- what exactly ?????? -->) %>
<% } %>

<%-- other stuff here...%>
<input type="submit" />
<% } %>

我的 Controller 发布方法:

[HttpPost]
public ActionResult Create(PageViewModel viewModel) {
// do stuff with other fields

// I would like to do something like:
foreach (var item in selectedCheckBoxes) {
// do stuff
}
}

我似乎无法让它工作。我的基本问题以评论的形式混合在代码片段中,但回顾一下:

  • 我的 View 模型还好吗? (我是否需要添加任何内容来捕获所选的内容,而不是简单地显示列表?)
  • 我究竟应该在 View 中放置什么来呈现每个复选框?
  • 如何在发布后访问 Controller 中选中的复选框?

最佳答案

你见过吗:http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx

我们基本上编写了自己的控件来呈现 HTML

<label for="Products"> Select Products </label>
<ul class="checkBoxList">
<li>
<input type="hidden" value="0" name="Products.Index">
<input type="checkbox" value="3424" name="Products[0].Id" id="Products0">
<label for="Products0">iPod touch 3rd Generation</label>
</li>
<li>
<input type="hidden" value="1" name="Products.Index">
<input type="checkbox" value="3123" name="Products[1].Id" id="Products1">
<label for="Products1">Creative Zen</label>
</li>
</ul>
</div>

模型看起来不错,我们写了一个自定义助手,所以我们的 aspx 页面看起来像:

<%= Html.DropDownFor(m=>m.products) %>

如果您关注 phil haacks 帖子,您的模型应该会自动绑定(bind)到您的 Controller 中。

关于c# - 复选框和模型绑定(bind)的动态列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3234973/

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