我正在开发一个页面,该页面在 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);
}
关于c# - 如何处理复选框列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26035457/