【问题标题】:Move data from a view to another view将数据从一个视图移动到另一个视图
【发布时间】:2021-01-10 02:03:55
【问题描述】:

我想将数据从 IActionResult 移动到另一个 IActionResult。我已将产品详细信息的数据存储在返回视图 (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);
    }

这是我对Details Action Method的看法:

@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>

【问题讨论】:

    标签: view controller asp.net-core-mvc


    【解决方案1】:

    首先,您的详细信息视图中的页面模型应该是Product,而不是List&lt;Product&gt;

    @model Product
    

    由于 cdd 是您数据库表中的一条记录,您可以在 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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-27
      • 1970-01-01
      • 2021-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多