【问题标题】:Getting items form json and pass it as parameter in Blazor wasm从 json 获取项目并将其作为 Blazor wasm 中的参数传递
【发布时间】:2021-11-16 20:31:49
【问题描述】:

您好,我在 Blazor Web 组件中遇到了我的对象问题。 我有我的组件 ShipmentsTable 我将货件作为参数传递,但是有一个问题,因为我的 GetShipmentResult 看起来像这样[![在此处输入图像描述][1]][1]

<ShipmentsTable Shipments="@shipments.Items"></ShipmentsTable>

@code {
    private GetShipmentsResult shipments;

protected override async Task OnInitializedAsync()
{
    shipments = await HttpClient.GetFromJsonAsync<GetShipmentsResult>("https://localhost:5001/api/shipment?page=0");
}

private void NavigateToShipmentForm()
{
    NavigationManager.NavigateTo("addShipment");
}

}

我的 GetShipmentResult 对象

public class GetShipmentsResult
    {   
        public List<ShipmentVm> Items { get; set; } = new List<ShipmentVm>();
        public int TotalCount { get; set; }
    }

和Json响应表单Api

    {
        "items": [
            {
                "description": "second",
                "expectedTimeOfArrival": "2021-09-10T17:56:24.589",
                "expectedTimeOfDeparture": "2021-09-10T17:56:24.589",
                "actualTimeOfArrival": null,
                "actualTimeOfDeparture": null,
                "isDone": false,
                "placeOfArrivalId": 1,
                "placeOfArrival": null,
                "placeOfDepartureId": 1,
                "placeOfDeparture": null,
                "hash": "tyac2NpISm4t/DjyGhTKnN11EKjsewr5ydNhjrzblMw=",
                "index": 0,
                "prevHash": "LX3OqOZpt88fvTIQfoiLs0zzoEbNBMCMdV1QsqNVRRk=",
                "timeStamp": "2021-09-23T11:52:51.8174364"
            }
            ],
"totalCount" : 1
}

public class ShipmentVm
    {
        public string Description { get; set; }
        public DateTime ExpectedTimeOfArrival { get; set; }
        public DateTime ExpectedTimeOfDeparture { get; set; }
        public DateTime? ActualTimeOfArrival { get; set; }
        public DateTime? ActualTimeOfDeparture { get; set; }
        public bool IsDone { get; set; }
        public int PlaceOfArrivalId { get; set; }
        public int PlaceOfDepartureId { get; set; }
        public byte[] Hash { get; set; }
        public byte[] PrevHash { get; set; }
        public int Index { get; set; }
        public DateTime TimeStamp { get; set; }
    }

blazor.webassembly.js:1 关键:Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100] 未处理的异常呈现组件:对象引用未设置为对象的实例。 System.NullReferenceException:对象引用未设置为对象的实例。 在 Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.UpdateRetainedChildComponent(DiffContext& diffContext,Int32 oldComponentIndex,Int32 newComponentIndex) 在 Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.AppendDiffEntriesForFramesWithSameSequence(DiffContext& diffContext,Int32 oldFrameIndex,Int32 newFrameIndex) 在 Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.AppendDiffEntriesForRange(DiffContext& diffContext,Int32 oldStartIndex,Int32 oldEndIndexExcl,Int32 newStartIndex,Int32 newEndIndexExcl) 在 Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.ComputeDiff(渲染器渲染器,RenderBatchBuilder batchBuilder,Int32 componentId,ArrayRange1 oldTree, ArrayRange1 newTree) 在 Microsoft.AspNetCore.Components.Rendering.ComponentState.RenderIntoBatch(RenderBatchBuilder batchBuilder,RenderFragment renderFragment) 在 Microsoft.AspNetCore.Components.RenderTree.Renderer.RenderInExistingBatch(RenderQueueEntry renderQueueEntry) 在 Microsoft.AspNetCore.Components.RenderTree.Renderer.ProcessRenderQueue()

@using TrakkerWASM.Client.Models
@using TrakkerWASM.Client.Models.TestVm
<h3>Shipments table</h3>

<table class="table table-striped">
    <thead>
        <tr>
            <th>Is done</th>
            <th>Time stamp</th>
            <th>Hash</th>
            <th>Previous hash</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var shipment in Shipments)
        {
            <tr>
                <td>@shipment.IsDone</td>
            </tr>
            <tr>
                <td>@shipment.TimeStamp</td>
            </tr>
            <tr>
                <td>@shipment.Hash.ToString()</td>
            </tr>
            <tr>
                <td>@shipment.PrevHash</td>
            </tr>
        }
    </tbody>
</table>

@code {
    [Parameter]
    public List<ShipmentVm> Shipments { get; set; }
}

【问题讨论】:

  • 你也可以发布 ShipmentVm 课程吗?
  • @Serge 是的,请。您还想要浏览器控制台的 blazor 错误表单吗?
  • 问题是什么?该屏幕截图显示没有什么奇怪的。 GetShipmentsResult.Items 属性包含单个 ShipmentVm
  • @Kamil 谢谢,如果你也发布错误就好了
  • @PanagiotisKanavos 我的问题是为什么当我作为参数 shipments.Items 传递给 ShipmentsTable 组件时,我得到的对象引用未设置为对象的实例

标签: c# .net blazor-webassembly


【解决方案1】:

GetFromJsonAsync 有时会给出奇怪的结果。尝试使用 Newtonsoft.Json,也许你会看到不同。我通常使用这样的算法

protected override async Task OnInitializedAsync()
{

var response = await HttpClient.GetAsync("https://localhost:5001/api/shipment?page=0");

    if (response.IsSuccessStatusCode)
    {
        var stringData = await response.Content.ReadAsStringAsync();
        shipments = JsonConvert.DeserializeObject<GetShipmentsResult>(stringData);
    }
 
}

由于反序列化器无法识别字节[]

,因此您还必须更改您的虚拟机
public string Hash { get; set; }
 public string PrevHash { get; set; }

或者你可能需要这样的东西

[JsonProperty("hash")]
public string HashString { get; set; }
[JsonProperty("prevHash")]
public string PrevHashString { get; set; }

public byte[] Hash { 
get { return Convert.FromBase64String(HashString);} 
set { HashString=  System.Text.Encoding.UTF8.GetString(value, 0, value.Length); }
}
public byte[] PrevHash { 
get { return Convert.FromBase64String(PrevHashString);} 
set { PrevHashString=  System.Text.Encoding.UTF8.GetString(value, 0, value.Length); } 
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-23
    • 2022-01-07
    • 2020-02-28
    • 1970-01-01
    • 2016-09-02
    • 2011-02-25
    相关资源
    最近更新 更多