2011-05-30 55 views
1

我有一个MVC 3应用程序和一个页面,用户可以请求有关我们服务的更多信息。ASP.NET 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 
} 

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

回答

2

如果您前缀与列表的名字和他们在方括号索引你的产品对象的字段的名称,然后MVC将结合你的名单

Eg

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

在这种情况下,产品对象需要叫InterestedInCheckbox

一个布尔值属性

你应该从0开始了顺索引这种方法的工作(你将需要隐藏字段和一个稍微不同的技术,如果这是不是这样)

最后,我想使用HTML复选框帮手后所需的复选框,因为这将输出生成的复选框一个隐藏字段:

(下面的代码是未经测试)

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

可能只是想在产品[{0}]周围加双引号。好的建议,但。 – GONeale 2011-05-31 00:21:45

+0

感谢您指出错过的引号! – 2011-05-31 00:57:46

+0

没问题.. :) – GONeale 2011-06-01 00:48:35

0

我想你想要的是这样的:

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