<% foreach (FoodMenu f in (IEnumerable)ViewData.Model)
{
%>
<ul >
<li><%= Html.Encode(f.ProductId) %> </li>
<li><%= Html.Encode(f.Name) %></li>
<li><%= Html.Encode(f.Price) %> </li>
<li><%= Html.CheckBox("Selected") %></p></li>
</ul>
</div>
<% } %>
我想将所选项目添加到数据库
答案 0 :(得分:1)
将所选产品的ID编码到复选框的名称中。
<%= Html.CheckBox("Selected_" + f.ProductId) %>
在服务器端,遍历ValueProviderKeys并查找选择并从所选的那些中提取产品ID。
foreach (var key in this.ValueProvider.Keys.Where( k => k.StartsWith( "Selected_" ) )
{
// for a checkbox I think this is something like true,false if the
// visible checkbox is checked. There is an invisible checkbox
// (set to false), that is checked by default so you get both when
// the true checkbox is checked.
bool selected = this.ValueProvider[key].AttemptedValue.Contains("true");
int productID = int.Parse( key.Replace("Selected_",null) );
...store selected product id in db...
}
答案 1 :(得分:0)
最好的方法是使用模型绑定作为复选框列表,请参见此处的帖子:
http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx