【问题标题】:how to handle a list of checkbox?如何处理复选框列表?
【发布时间】:2014-11-20 01:00:39
【问题描述】:

我正在开发一个页面,该页面在视图上显示来自服务的数据并允许用户对其进行过滤。 有一个国家列,允许用户过滤。

我无法找到一种创建复选框列表的方法,以便我可以在一个参数中获取所有选定的值,例如字符串 [] 国家/地区(在操作方法中)。

不能使用经典方式:

<input type="checkbox" name="countries" value="USA" />USA<br />
<input type="checkbox" name="countries" value="Canada" />Canada<br />

这确实会传递 URL 中的值,但不会在回发时将它们设置回(在回发时保持检查)。

我尝试使用 checkboxlist (http://goo.gl/TUvZzu),但对我的 Modal 来说似乎很复杂。

因为我的模型是一个非常直接的模型:

public string Title { get; set; }
public string Website { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string Zip { get; set; }
public string State { get; set; }
public string Country { get; set; }

感谢您的宝贵时间和帮助。

【问题讨论】:

  • 你要使用jquery吗????
  • @Kartikeya:我可以,直到它解决了目的,但我需要将这些值发送到 Action Method 并将它们设置回来(保持状态)。
  • 您是否有理由使用复选框列表被出售?为什么不能硬编码复选框并在控制器中构建string[]
  • @MatthewHaugen :国家/地区列表在每次过滤时都会发生变化,我仍然可以通过迭代 Modal 来编写它们,但是我如何将值作为字符串 [] 提供给控制器,并通过剃须刀处理来设置值正确回发。 ?
  • 创建一个视图模型,代表您想要显示和回发的内容

标签: c# asp.net-mvc asp.net-mvc-4 checkbox checkboxlist


【解决方案1】:

您需要在视图模型中包含一组国家/地区来保存选定的值并允许它们在帖子中发送。

我还将创建一个 Country 对象来保存 Id、Name 和 Selected 值。

为了使模型回发,您需要为视图中的每个项目编制索引,这允许模型绑定器拾取它。

模型

public class AModel
{
    public AModel()
    {
        Countries = new List<Country>();    
    }

    public string Title { get; set; }
    public string Website { get; set; }
    public string Address1 { get; set; }
    public string Address2 { get; set; }
    public string City { get; set; }
    public string Zip { get; set; }
    public string State { get; set; }
    public string Country { get; set; }
    // Country collection
    public List<Country> Countries { get; set; }

}

    public class Country
    {
        public int ID { get; set; }
        public string Name { get; set; }                
        public bool Checked { get; set; }           
    }

查看循环

@for(var i = 0; i < Model.Countries.Count; i++)
{

    <dt>
        @Html.HiddenFor(m => Model.Countries[i].ID)
        @Html.HiddenFor(m => Model.Countries[i].Name)
        @Html.CheckBoxFor(m => Model.Countries[i].Checked)
    </dt>
    <dd>
        @Model[i].Name
    </dd>

}

注意 for 循环而不是 foreach 以启用模型绑定和隐藏字段以允许将值发送回控制器

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

管制员职位

[HttpPost]
public ActionResult Index(AModel model)
{
    //All the selected countries are available in the model

    return View(model);
}

Working example

【讨论】:

  • 非常感谢您提供详尽的回答,我正在尝试了解如何将其放入我的模态中,对于它实际上表示国家的动物名称感到抱歉,但我从某个地方复制了代码示例,我已经更新了帖子。
  • 如果您不介意,请相应地更新答案值,以便更好地理解,非常感谢一次。
  • @VishalSachdeva 您好,我已经用描述更新了代码,并为您将其更改为 Country。
  • 没问题。祝你好运。 @VishalSachdeva
  • 您好,我应该提到我需要 QS 中的值,以便人们可以共享过滤后的结果。路由值映射为 Action 方法的参数以过滤模型。这个例子不能解决这个目的:( ?
猜你喜欢
  • 2022-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-25
  • 2021-11-06
  • 1970-01-01
  • 2021-03-05
  • 1970-01-01
相关资源
最近更新 更多