【问题标题】:How to send complex object to blazor page如何将复杂对象发送到 Blazor 页面
【发布时间】:2021-09-16 14:42:53
【问题描述】:

我想将一个复杂对象从另一个转发到一个 Blazor 页面。让我们考虑以下三个类。

public class Order
{
    
    public Supplier { get; }
    public List<Product> Products { get; } = new List<Product>();
    public decimal TotalValue { get; set; }
    
    public Order(Supplier supplier)
    {
        Supplier = supplier;
    }
}

public class Supplier
{
    public int SupplierId { get; set; }
    public int DeliveryConditions { get; set; }
    public int PaymentConditions { get; set; }
}

public class Product
{
    public int ProductId { get; set; }
    public int Quantity { get; set; }
}

现在我有两页。第一个允许用户选择供应商并根据供应商创建订单类型的对象。第二个页面应与此对象一起使用,并应允许用户编辑所有其他订单详细信息,供应商除外。

在我的情况下,我需要先选择供应商,以便能够过滤掉供应商无法交付的所有产品。

我怎样才能做到这一点?

谢谢!

【问题讨论】:

标签: c# asp.net-core blazor blazor-server-side


【解决方案1】:

您是否考虑过使用单例服务?这可以通过使用@inject 和作为单例在所有页面上使用。您可以在选择供应商并生成订单的页面中设置供应商并订购。并将其注入其他页面。

public class OrderService{
    public Order ActiveOrder {get;private set;}
    public Supplier ActiveSupplier {get;set;}
    public void GenerateOrder(Supplier s) {
        //...
    }
}

您必须在 Startup 中将 Service 注册为单例:

builder.Services.AddSingleton<OrderService>();

所以你可以在你的页面中使用它:

@inject OrderService MyOrderService​
private void SupplierSelected(Supplier s)
{
    MyOrderService.GenerateOrder(s);
}

【讨论】:

    【解决方案2】:

    你必须使用参数关键字,当第一个组件有数据时,它会加载到第二个组件: 在示例中,您放置的第一页将是供应商,当它完成时,您将其作为参数传递:

    @using Pages
    @page "/"
    
    <h1>First supplier page</h1>
    
    
    <label> Supplier Id</label>
    <input @bind="@sup.SupplierId" type="int"/>
    
    
    <button @onclick="() => this.done=true"> Submit </button>
    
    
    @if(done) { 
        
        <product supplier="sup"></product>
    }
    
    @code{
    public bool done=false;
    Supplier sup = new();    
    
    
    }
    

    在这里您可以看到如何将供应商作为参数传递给第二个 blazor 组件。 在此页面中,您可以随意使用您的对象。

    @using Pages
    <h3>Second page with supplier as parameter</h3>
    
    //whatever presentation
    @code {
            [Parameter]
        public Supplier supplier{ get; set; }
    
        //whatever logic
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-05
      • 2015-08-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多