如何使用ASP.NET MVC将所选项添加到数据库中

时间:2022-10-15 14:30:50
      <% 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> 

      <% } %>

I want to add the selected item into database

我想将所选项目添加到数据库中

2 个解决方案

#1


Encode the id of the product that is selected into the name of the check box.

将所选产品的ID编码到复选框的名称中。

<%= Html.CheckBox("Selected_" + f.ProductId) %>

The on the server side, iterate through the ValueProviderKeys and find selections and extract the product id from the ones that are selected.

在服务器端,遍历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...
}

#2


Neatest way is to use model binding for your list of checkboxes, see post here:
http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx

最好的方法是使用模型绑定作为复选框列表,请参见此处的帖子:http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx

#1


Encode the id of the product that is selected into the name of the check box.

将所选产品的ID编码到复选框的名称中。

<%= Html.CheckBox("Selected_" + f.ProductId) %>

The on the server side, iterate through the ValueProviderKeys and find selections and extract the product id from the ones that are selected.

在服务器端,遍历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...
}

#2


Neatest way is to use model binding for your list of checkboxes, see post here:
http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx

最好的方法是使用模型绑定作为复选框列表,请参见此处的帖子:http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx