将数据从一个视图移动到另一个视图

Move data from a view to another view

我想将数据从一个 IActionResult 移动到另一个 IActionResult。我已将产品详细信息的数据存储在 return 视图 (cdd) 中。如何将它存储到 Tempdata 中以便将其传递给另一个视图? 这是我的代码:

[HttpGet]
    public IActionResult Details(int id)
    {
        string sql = String.Format(@"SELECT * FROM WBProduct 
                               WHERE Id = {0}", id);
        List<Product> lstProduct = DBUtl.GetList<Product>(sql);

        if (lstProduct.Count == 0)
        {
            TempData["Message"] = $"Product #{id} not found";
            TempData["MsgType"] = "warning";
            return Index();
        }
        else
        {
            Product cdd = lstProduct[0];
            return View(cdd);
            

            
        }
    }

我想在这个动作方法中调用数据'cdd'。

public IActionResult Create(Product product)
    {
        return View("Create", product);
    }

这是我对详细操作方法的看法:

@model List<Product>

@if (TempData["Message"] != null)
{
 <div class="alert alert-@TempData["MsgType"]">
    @TempData["Message"]
</div>
}

<table class="table table-condensed table-hover">
<tr>
    <th scope="col">ID</th>
    <th scope="col">Product</th>
    <th scope="col">Price</th>
    <th scope="col">Quantity</th>

</tr>


<tr>
    <td>@ViewData["ID"]</td>
    <td>@ViewData["Product"]</td>
    <td>@ViewData["Price"]</td>
    <td>@ViewData["Quantity"]</td>
    <td>
        <a asp-controller="Product"
           asp-action="Delete">
            Delete
        </a>
    </td>

    <td>
        <a asp-controller="Product"
           asp-action="Checkout">
            Checkout
        </a>
    </td>

</tr>

首先,详细信息视图中的页面模型应该 Product 而不是 List<Product>

@model Product

因为 cdd 是来自您的数据库 table 的记录,您可以在 Details.cshtml 中设置一个锚点以将 id 发送到 Create 操作。然后像 Details 操作中那样从数据库中获取产品。

Details.cshtml:

<a asp-controller="Product" asp-action="Create" asp-route-id="@ViewData["ID"]">
        Create
</a>

创建:

[HttpGet]
public IActionResult Create(int id)
{
    string sql = String.Format(@"SELECT * FROM WBProduct 
                           WHERE Id = {0}", id);
    List<Product> lstProduct = DBUtl.GetList<Product>(sql);
    Product cdd = lstProduct[0];
    return View("Create", product);
}