如何使用 entity framework 在 asp.net 中选中复选框

how to get selected checkbox in asp.net using entity framework

我是 asp.net mvc.I 的新手,我有一个复选框列表,我希望在选中复选框时显示一个新的选中复选框列表。 我的代码 Product.cs 代码:

public class Product
{
    public int ProductID { get; set; }
    public string ProductName { get; set; }
    public int Price { get; set; }
    public bool Checked { get; set; }
    public virtual ICollection<Purchase> Purchases { get; set; }
}

我的看法:

<h2>Product Lists</h2>
@using (Html.BeginForm())
{

    <table class="table">
        <tr>
            <th>
                Product ID
            </th>
            <th>
                Product Name
            </th>
            <th>
                Price
            </th>
            <th></th>
        </tr>
        @for (var i = 0; i < Model.Count(); i++)
        {
            <tr>
                <td>
                    @Html.DisplayFor(x => x[i].ProductID)
                </td>
                <td>
                    @Html.DisplayFor(x => x[i].ProductName)
                </td>
                <td>
                    @Html.DisplayFor(x => x[i].Price)
                </td>
                <td>
                    @Html.CheckBoxFor(x => x[i].Checked, new { Style = "vertical-align:3px}" })
                </td>
            </tr>
        }

    </table>

    <input type="submit" value="Purchase" class="btn btn-default" />
}

这是我的控制器 code.I 希望在新页面中选中复选框时显示选中的复选框。 我的操作结果:

    public ActionResult Index()
    {
        return View(db.Products.ToList());
    }

    [HttpPost]
    public ActionResult Index(List<Product> list)
    {
        return View(list);
    }
@using (Html.BeginForm())

{

<table class="table">
    <tr>
        <th>
            Product ID
        </th>
        <th>
            Product Name
        </th>
        <th>
            Price
        </th>
        <th></th>
    </tr>

    @for (var i = 0; i < Model.Count(); i++)
    {
        <tr>
            <td>
                @Html.DisplayFor(x => x[i].ProductID)
            </td>
            <td>
                @Html.DisplayFor(x => x[i].ProductName)
            </td>
            <td>
                @Html.DisplayFor(x => x[i].Price)
            </td>
            <td>
                @Html.CheckBoxFor(x => x[i].Checked, new { Style = "vertical-align:3px}" })
            </td>
        </tr>
    }

</table>

如果您已经有了一个包含所有 checked/unchecked 属性的列表,并且只想在新视图中显示选中的记录,您可以将列表存储在 TempData 中并重定向到一个操作将使用您的列表:

public ActionResult Index()
{
    return View(db.Products.ToList());
}

[HttpPost]
public ActionResult Index(List<Product> list)
{
    TempData["CheckedRecords"] = list.Where(x=>x.Checked).ToList(); //Don't forget to add 'using System.Linq;'!
    return RedirectToAction("MyOtherView");
}

public ActionResult MyOtherView()
{
    var checkedRecords = (List<Product>)TempData["CheckedRecords"];
    return View(checkedRecords);
}