如何处理复选框列表

本文关键字:复选框 列表 处理 何处理 | 更新日期: 2023-09-27 18:24:17

我正在开发一个页面,该页面在View上显示来自服务的数据,并允许用户对其进行筛选。有一个国家栏,允许用户进行筛选。

我无法找到创建复选框列表的方法,这样我就可以在一个类似字符串[]的国家(在操作方法中)中获取所有选定的值。

不能使用经典方式:

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

这确实传递了URL中的值,但不会在postback上设置它们(在postback中保持检查)。

我试过使用复选框列表(http://goo.gl/TUvZzu)但对我的莫代尔来说似乎很复杂。

由于我的是一个非常直接的模型:

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对象来保存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);
}

工作示例