gpt4 book ai didi

asp.net-mvc-2 - 将 KeyValuePair 列表绑定(bind)到复选框

转载 作者:行者123 更新时间:2023-12-01 11:06:12 25 4
gpt4 key购买 nike

我在 C# 中使用 ASP.Net MVC。我有一个模型,其中有一个过滤条件成员。这个成员是一个 IList>。该键包含要显示的值,该值表明是否选择了此过滤器。我想将其绑定(bind)到我 View 中的一堆复选框。我就是这样做的。

<% for(int i=0;i<Model.customers.filterCriteria.Count;i++) { %>
<%=Html.CheckBoxFor(Model.customers.filterCriteria[i].value)%>&nbsp;
<%=Model.customers.filterCriteria[i].key%>
<% } %>

这会正确显示所有复选框。但是当我在 Controller 中提交我的表单时,无论我在 View 中选择什么,我都会得到 null 的过滤条件。

来自 this发布我得到创建单独属性的提示。但这对 IList 将如何工作……?有什么建议吗?

最佳答案

KeyValuePair<TKey, TValue> 的问题structure 是它具有私有(private) setter ,这意味着默认模型绑定(bind)器无法在 POST 操作中设置它们的值。它有一个特殊的构造函数,需要使用它来允许传递键和值,但是默认模型绑定(bind)器当然不知道这个构造函数并且它使用默认的,所以除非你为这种类型编写一个自定义模型绑定(bind)器你将无法使用它。

我建议您使用自定义类型而不是 KeyValuePair<TKey, TValue> .

一如既往,我们从 View 模型开始:

public class Item
{
public string Name { get; set; }
public bool Value { get; set; }
}

public class MyViewModel
{
public IList<Item> FilterCriteria { get; set; }
}

然后是一个 Controller :

public class HomeController : Controller
{
public ActionResult Index()
{
return View(new MyViewModel
{
FilterCriteria = new[]
{
new Item { Name = "Criteria 1", Value = true },
new Item { Name = "Criteria 2", Value = false },
new Item { Name = "Criteria 3", Value = true },
}
});
}

[HttpPost]
public ActionResult Index(MyViewModel model)
{
// The model will be correctly bound here
return View(model);
}
}

和对应的~/Views/Home/Index.aspx查看:

<% using (Html.BeginForm()) { %>
<%= Html.EditorFor(x => x.FilterCriteria) %>
<input type="submit" value="OK" />
<% } %>

最后我们为 ~/Views/Shared/EditorTemplates/Item.ascx 中的 Item 类型编写了一个定制的编辑器模板。或 ~/Views/Home/EditorTemplates/Item.ascx (如果此模板仅特定于 Home Controller 且未重复使用):

<%@ Control 
Language="C#"
Inherits="System.Web.Mvc.ViewUserControl<AppName.Models.Item>"
%>
<%= Html.CheckBoxFor(x => x.Value) %>
<%= Html.HiddenFor(x => x.Name) %>
<%= Html.Encode(Model.Name) %>

我们已经完成了两件事:清理丑陋的 View for循环并使模型绑定(bind)器成功绑定(bind) POST 操作中的复选框值。

关于asp.net-mvc-2 - 将 KeyValuePair 列表绑定(bind)到复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5676344/

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