【问题标题】:.NET core MVC that uses the EF Framework - Pass the data from one controller another使用 EF 框架的 .NET 核心 MVC - 将数据从一个控制器传递到另一个控制器
【发布时间】:2021-12-07 08:21:41
【问题描述】:

我第一次使用带有 EF 的 ASP.NET Core MVC 进行 Web 应用开发。我在 SQL Server 数据库中有两个表 CustomerInventory

我做了Scaffold-DbContext 并为两个表生成了模型/控制器和视图。我的要求是,从网格上每个客户的Customer 索引页面中,我添加了一个选择按钮,当单击此选择按钮时,我需要将选定的客户数据传递给库存控制器并在顶部显示客户选择库存索引页面和下面的我显示带有库存表的网格。

我在这里使用TempData。在客户表上,我添加了选择按钮

<td>
    <a asp-action="passToInventory" asp-route-id="@item.CustomerId">Select</a>
</td>

CustomersController:

public async Task<IActionResult> passToInventory(int? id)
{
    if (id == null)
    {
        return NotFound();
    }

    Customer customer_data = await _context.Customers.FindAsync(id);

    TempData["custdata"] = customer_data;

    return RedirectToAction("Index", "Inventories");
}

现在在Index 方法中的InventoriesController 上,我进行了更改,例如访问通过的TempData

public async Task<IActionResult> Index()
{
    Customer cust_data = TempData["custdata"] as Customer;
    return View(await _context.Inventories.ToListAsync());
}

我尝试创建一个模型类,这样我就可以在Inventory Index 页面上同时使用客户和库存列表,如下所示:

public class CustomerInventoryCollectionDataModel
{
    public Customer CustomerData { get; set; }
    public List<Inventory> Inventorys { get; set; }
}

我无法在库存的索引页面上检索到数据

 @model IEnumerable<JAXSurplusMouseApp.Models.CustomerInventoryCollectionDataModel>
  
//show the selected customer data from the previous page 
  unable to access the customer data here and show it 

//table for the Inventory list 
<tbody>
    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Inventorys.QuantityAvailable)
            </td>
         </tr>
     }

请建议我如何在同一视图中检索两个模型并将它们显示在同一页面中。非常感谢任何帮助

【问题讨论】:

    标签: c# asp.net-mvc entity-framework asp.net-core entity-framework-core


    【解决方案1】:

    动作

    public async Task<IActionResult> Index()
     {
      Customer custData = TempData["custdata"] as Customer;
      var inventories =await _context.Inventories.ToListAsync();
      var model= new CustomerInventoryCollectionDataModel
    {
       CustomerData = custData,
        Inventorys =inventories 
    };
    
      return View(model);
     }
    

    查看

    @model JAXSurplusMouseApp.Models.CustomerInventoryCollectionDataModel
      
    //show the selected customer data from the previous page 
    //  using  @Model.CustData
     
    @Html.DisplayFor(model => model.CustData.Name)
    
    ....and so on
    
    //table for the Inventory list 
    <tbody>
        @foreach (var item in Model.Inventorys)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.QuantityAvailable)
                </td>
             </tr>
         }
    

    但恐怕您需要序列化客户,所以我使用它似乎更有效

    public async Task<IActionResult> passToInventory(int? id)
     {
       if (id == null)
       {
         return NotFound();
       }
      
       return RedirectToAction("Index", "Inventories",new { id });
    
     }
    
    

    动作

    public async Task<IActionResult> Index(int? id)
     {
     if(id==null) return ...error
    
      Customer custData =   await _context.Customers.FindAsync(id);
      var inventories =await _context.Inventories.ToListAsync();
      var model= new CustomerInventoryCollectionDataModel
    {
       CustomerData = custData,
        Inventorys =inventories 
    };
    
      return View(model);
     }
    

    或者如果您出于某种原因需要使用 TempData 客户,您可以在代码中使用它

    var customerData = await _context.Customers.FindAsync(id);
    
    TempData["custdata"] =
    System.Text.Json.JsonSerializer.Serialize( customerData;)
    
    //index
     Customer custData = System.Text.Json.JsonSerializer.Deserialize<Customer> ( 
    TempData["custdata"].ToString());
    

    PS

    我不知道您在 passToInventory 操作中是否有更多代码然后发布,但它现在看起来的方式恕我直言,您可以立即进入索引

    <td>
     <a asp-action="Index" asp-controller="Inventories" asp-route-id="@item.CustomerId">Select</a>
    </td>
    

    【讨论】:

    • 非常感谢。我试过了,但是当我点击选择按钮时,我收到了InvalidOperationException: The 'Microsoft.AspNetCore.Mvc.ViewFeatures.Infrastructure.DefaultTempDataSerializer' cannot serialize an object of type 'JAXApp.Models.Customer'. Microsoft.AspNetCore.Mvc.ViewFeatures.Infrastructure.DefaultTempDataSerializer.Serialize(IDictionary&lt;string, object&gt; values) 之类的错误
    • @trx 我预料到了这一点,所以我正在更新我的答案
    • 再次感谢您
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多