【问题标题】:Blazor not refreshing componentBlazor 不刷新组件
【发布时间】:2020-05-09 12:18:23
【问题描述】:

[Blazor 客户端托管]

我有一个从 API 加载数据的简单表格工作正常...现在我需要应用过滤器并重新加载表格以显示新数据/列表;

解决方案结束

index.razor

    @inherits PersonBase;

//---show 3 items but after filter no change--    
<h2>list size: @PersonList.Count()</h2> 
<EditForm Model="@Obj ">
    <div class="col-md-12">
        <div class="well">
            <table class='table borderless'>
                <tr>
                    <td colspan="2" style="text-align: right">
                        <InputText @bind-Value="@Search" class="form-control input-sm" style="width:200px;margin-bottom:0px" type="text" name="input3" placeholder="Pesquisar por:" />
                        <button class="btn btn-info" @onclick="@(() => LoadItems(@Search))">
                            <i class="fas fa-search"></i>
                        </button>
                    </td>
                </tr>
            </table>
        </div>
    </div>
</EditForm>

    <table class="table">
        <thead>
            <tr>
                <th>Id</th>
                <th>Name</th>

            </tr>
        </thead>
        <tbody>
            @foreach (var person in PersonList)
            {
            <tr>
                <td>@person.Id</td>
                <td>@person.Name</td>
            </tr>
            }
        </tbody>
    </table>

PersonBase.cs

namespace MyProject.Client.Pages.PersonComponent
{
    public class PersonBase : ComponentBase
    {
        [Inject] public HttpClient Http { get; set; }
        [Inject] NavigationManager Navigation { get; set; }

        [Parameter] public string Search { get; set; } = string.Empty;
        protected IEnumerable<Person> Itens { get; set; }
        [Parameter] public List<Person> PersonList { get; set; }
        public int idObj;

        [Parameter] public Person Obj { get; set; }

        protected override async Task OnInitializedAsync()
        {
            Obj = new Person();
            await LoadItems(null); //--Loading all items
            
            Console.WriteLine("OnInitializedAsync => " + PersonList.Count);
        }

        //--LOAD BY WEBAPI--
        protected async Task LoadItems(string search)
        {
            try
            {
                var httpResponse = await Http.GetAsync($"api/person/list/{search}");

                if (httpResponse.IsSuccessStatusCode)
                {
                    var responseString = await httpResponse.Content.ReadAsStringAsync();

                    PersonList = JsonSerializer.Deserialize<List<Person>>(responseString,
                    new JsonSerializerOptions()
                    {
                        PropertyNameCaseInsensitive = true
                    });

                    Itens = PersonList;
                    Console.WriteLine("LoadItems => PersonList => " + PersonList.Count);

                    await InvokeAsync(() => StateHasChanged()).ConfigureAwait(false);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}

PersonController.cs

    [HttpGet("list/{search}")]
    public async Task<ActionResult<List<Person>>> GetByAll(string search)
    {
        try
        {
        //--Loading all--
            if (string.IsNullOrEmpty(search))
            {
                return await _context.Person
                    .AsNoTracking()
                    .Take(3)
                    .ToListAsync();
            }
            else
            {
            //--filtered--
                return await _context.Person
                    .AsNoTracking()
                    .Where(n => n.Name.ToLower().Contains(search.ToLower()))
                    .Take(3)
                    .ToListAsync();
            }
        }
        catch (Exception)
        {
            throw;
        }
    }

但是表格没有加载新数据。我现在可以尝试什么?

已解决: 问题是没有 [FromQuery] 的控制器:

PersonControler.cs

[HttpGet]
[Route("list")]
public async Task<ActionResult<List<Pessoa>>> GetByAll([FromQuery]string search = "")

现在我可以:

var httpResponse = await Http.GetAsync($"api/person/list?search={search}");

就像说的:https://docs.microsoft.com/pt-br/aspnet/core/web-api/?view=aspnetcore-3.1

【问题讨论】:

  • @Henk Holterman,如果您查看整个示例,很明显您的怀疑是错误的,这只是代码中的一个错字。
  • @Henk Holterman 你在说什么?所有 c# 代码都在代码隐藏中。我现在编辑了。
  • 你的 PersonBase.cs 是从 ComponentBase 派生的吗?
  • @Štefan Bartoš 是的,公共类 PersonBase:ComponentBase。如何在控制台中显示,所有后端进程都工作,但不显示/刷新
  • @Henk Holterman 感谢您的“帮助”,伙计。解决了。问题出在没有 [FromQuery] 的 PersonController 中

标签: c# asp.net-web-api razor entity-framework-core blazor


【解决方案1】:

当你用异步代码替换属性引用时调用StateHasChanged

public List<Person> ListPeople { get; set; }

protected async Task LoadPeople(string search)
{
    try
    {
        var httpResponse = await Http.GetAsync($"api/people/list/{search}");

        if (httpResponse.IsSuccessStatusCode)
        {
            var responseString = await httpResponse.Content.ReadAsStringAsync();

            ListPeople = JsonSerializer.Deserialize<List<Person>>(responseString,
            new JsonSerializerOptions()
            {
                PropertyNameCaseInsensitive = true
            });

            Itens = ListPeople;
            Console.WriteLine("Count=> " + ListPeople.Count); // returning all 3 objects 

            // informs the component its state a changed and it should rerender
            await InvokeAsync(() => StateHasChanged())
                        .ConfigureAwait(false);
        }
    }
}

而且你的@foreach 中不应该有@ListPeople

...
@foreach (var person in ListPeople)
...

编辑第二个选项

不是替换列表引用,而是清除并添加项目:

public List<Person> ListPeople { get; } = new List<Person>();

protected async Task LoadPeople(string search)
{
    try
    {
        var httpResponse = await Http.GetAsync($"api/people/list/{search}");

        if (httpResponse.IsSuccessStatusCode)
        {
            var responseString = await httpResponse.Content.ReadAsStringAsync();

            var newItems = JsonSerializer.Deserialize<List<Person>>(responseString,
            new JsonSerializerOptions()
            {
                PropertyNameCaseInsensitive = true
            });

            ListPeople.Clear();
            ListPeople.AddRange(newItems);

            Itens = ListPeople;
            Console.WriteLine("Count=> " + ListPeople.Count); // returning all 3 objects 

            // informs the component its state a changed and it should rerender
            await InvokeAsync(() => StateHasChanged())
                        .ConfigureAwait(false);
        }
    }
}

【讨论】:

  • 来自火星的@agua。不工作,朋友。更多其他想法?
  • 是的,不要替换列表引用,而是执行.Clear .AddRange(newItems)
  • 谢谢你的帮助,伙计。解决了。问题出在没有 [FromQuery] 的 PersonController 中。我在问题的页脚中发布了完整的解决方案。
猜你喜欢
  • 2020-12-20
  • 2021-12-25
  • 1970-01-01
  • 2020-10-17
  • 1970-01-01
  • 2022-10-04
  • 2019-11-02
  • 1970-01-01
  • 2019-11-15
相关资源
最近更新 更多