C# ASP.NET MVC 3-使用复选框选择项目

C# ASP.NET MVC 3-使用复选框选择项目,c#,asp.net-mvc,data-binding,asp.net-mvc-3,model-binding,C#,Asp.net Mvc,Data Binding,Asp.net Mvc 3,Model Binding,我有一个MVC3应用程序,其中有一个页面,用户可以在其中请求有关我们服务的更多信息 当用户从下拉列表中选择他们的状态时,我想使用jQueryAjax获取我们在该状态下提供的产品列表。对于每个产品,我希望在产品名称旁边显示一个复选框。然后用户可以选择他们感兴趣的产品 我想将所选产品绑定到此视图模型上的列表属性。因此,模型将具有名称、电子邮件等属性和列表属性。下面是我试图绑定到的模型类的一个示例: public class RequestInformationModel { public s

我有一个MVC3应用程序,其中有一个页面,用户可以在其中请求有关我们服务的更多信息

当用户从下拉列表中选择他们的状态时,我想使用jQueryAjax获取我们在该状态下提供的产品列表。对于每个产品,我希望在产品名称旁边显示一个复选框。然后用户可以选择他们感兴趣的产品

我想将所选产品绑定到此视图模型上的列表属性。因此,模型将具有名称、电子邮件等属性和列表属性。下面是我试图绑定到的模型类的一个示例:

public class RequestInformationModel
{
    public string Name { get; set; }
    public string Email { get; set; }
    public List<Product> Products { get; set; }
}

关于如何做到这一点有什么建议吗?非常感谢。

我想你想要的是这样的:

/* Handles ajax request */
[HttpPost]
public ContentResult(string selectedListBoxItem)
{
  string content = "";

  /* TODO: Query DB to get product suggestions based on selectedListBoxItem */

  content = "<input type='checkbox' id='productId1' name='productSuggestion' value='productId1'>";
  content += "<input type='checkbox' id='productId2' name='productSuggestion' value='productId2'>";
  content += "<input type='checkbox' id='productId2' name='productSuggestion' value='productId2'>";
  return Content(content);
}

 /* Handles final submit */
[HttpPost]
public ActionResult HandleSubmit(string nameOfCheckboxCollection)
{
  string[] arrayChecked = nameOfCheckboxCollection.Split(",");
  foreach(string s in arrayChecked ) { 
      Model.addProduct(s); 
   } 
}

如果在产品对象中的字段名称前面加上列表名称及其方括号中的索引,那么MVC将为您绑定列表

例如

在这种情况下,产品对象需要一个名为InterestedInChekBox的bool属性

你应该有从0开始的顺序索引,如果不是这样的话,你需要一个隐藏字段和一个稍微不同的技术

最后,我将使用Html复选框帮助器创建复选框,因为这将在所需的复选框之后输出一个隐藏字段:

以下代码未经测试

@for (var i = 0; i < Model.Count; i++)
{
    @Html.CheckBox(string.Format("Products[{0}]", i), Model[i])
}

可能只想在产品[{0}]周围添加双引号。好建议。非常感谢你的回答。
<input type="checkbox" name="Products[0].InterestedInCheckbox" />
<input type="checkbox" name="Products[1].InterestedInCheckbox" />
@for (var i = 0; i < Model.Count; i++)
{
    @Html.CheckBox(string.Format("Products[{0}]", i), Model[i])
}