【问题标题】:ASP.NET MVC 3 - Select Items Using Check BoxesASP.NET MVC 3 - 使用复选框选择项目
【发布时间】:2011-05-31 08:57:11
【问题描述】:

我有一个 MVC 3 应用程序,其中包含用户可以请求有关我们服务的更多信息的页面。

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

我想将选定的产品绑定到此视图的模型上的 List 属性。因此该模型将具有名称、电子邮件等属性和 List 属性。这是我尝试绑定的模型类的示例:

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

这是我将表单发布到的控制器方法:

public ActionResult RequestInformation(RequestInformationModel model)
{
    // do stuff
}

关于如何做到这一点的任何建议?非常感谢。

【问题讨论】:

    标签: c# asp.net-mvc data-binding asp.net-mvc-3 model-binding


    【解决方案1】:

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

    例如

    <input type="checkbox" name="Products[0].InterestedInCheckbox" />
    <input type="checkbox" name="Products[1].InterestedInCheckbox" />
    

    在这种情况下,Product 对象需要一个名为 InterestedInCheckbox 的 bool 属性

    您应该有从 0 开始的顺序索引才能使此方法起作用(如果不是这种情况,您将需要一个隐藏字段和稍微不同的技术)

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

    (以下代码未经测试)

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

    【讨论】:

    • 可能只想在Products[{0}] 周围添加双引号。不过建议很好。
    • 非常感谢您的回答。
    【解决方案2】:

    我想你想要的是这样的:

    /* 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); 
       } 
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-28
      • 1970-01-01
      • 1970-01-01
      • 2021-08-08
      • 1970-01-01
      • 1970-01-01
      • 2015-05-06
      • 1970-01-01
      相关资源
      最近更新 更多