繁体   English   中英

如何处理复选框列表?

[英]how to handle a list of checkbox?

我正在开发一个页面,该页面在View上显示服务中的数据并允许用户对其进行过滤。 有一列用于国家/地区,允许用户进行过滤。

我无法找到一种创建复选框列表的方法,这样我就可以像string []国家(在action方法中)那样在一个参数中获取所有选定的值。

无法使用经典方式:

<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; }

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

您需要在视图模型中包括一个国家/地区集合,以保存选定的值并允许其在帖子中发送。

我还将创建一个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);
}

工作实例

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM