c# - 如何处理复选框列表?

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

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

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

不能使用经典方式:

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

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

我尝试使用复选框列表( 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; }

感谢您的时间和帮助。

最佳答案

您需要在 View 模型中包含国家/地区集合,以保存选定的值并允许它们在邮件中发送。

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

为了将模型发回,您需要为 View 中的每个项目建立索引,这允许模型绑定(bind)器拾取它。

模型

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 来启用模型绑定(bind)和隐藏字段以允许将值发回 Controller

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

Controller 帖子

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

    return View(model);
}

Working example

关于c# - 如何处理复选框列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26035457/

相关文章:

asp.net-mvc - HtmlHelper扩展方法与局部 View ?

c# - POST 到 C# 时 JSON 对象为空

ajax - 从 Ajax 表单加载的 MVC4 WebGrid - 排序和分页时多次调用 Controller

C# dynamic + System.Reflection.Emit = 不混用?

c# - 为什么三元运算符不是这样工作的?

c# - 未找到 DBSet<entity> 类( Entity Framework 加载错误的 DLL?)

jquery - ajax 将数据发布到 MVC Controller 的日期

c# - J2EE 和 C#/.Net 在开发 Web 服务时的主要​​区别

c# - 使用反射和锁定正确实例化分配给私有(private)静态 volatile 变量的类

c# - 如何在请求验证进入 MVC 4 之前清理输入?