gpt4 book ai didi

c# - 如何在 blazor 中使用 select2 组件?

转载 作者:行者123 更新时间:2023-12-04 09:00:29 32 4
gpt4 key购买 nike

你好社区我正在尝试在 blazor 中使用 select2 组件,我从 github 举了一个例子,但事实是我迷失了如何用数据库中的记录填充组件
这是 Razor 页面,这是组件:

<span>Simple string example</span>
<Select2 TItem="string"
Id="simple-string-example"
Data="@SimpleStringList"
@bind-Value="@ValueSelected">
</Select2>
<span>Currently selected value: @ValueSelected</span>
<br />

@code {

private EditContext EditContext { get; set; }
private Select2<SomeInnerObject> ProvidedSelect2Ref { get; set; }
public SomeObject FakeObject { get; set; } = new SomeObject { SomeName = "Name" };
private List<string> SimpleStringList { get; set; } = new List<string>();
private List<SomeInnerObject> InnerObjectList { get; set; }
private string ValueSelected { get; set; }

private SomeInnerObject FooObject = new SomeInnerObject { InnerName = "Inner Foo" };

protected override void OnAfterRender(bool firstRender)
{
base.OnAfterRender(firstRender);
if (firstRender)
{
SimpleStringList.Add("Foo");
SimpleStringList.Add("Bar");
SimpleStringList.Add("Baz");

InnerObjectList = new List<SomeInnerObject> { FooObject, new SomeInnerObject { InnerName = "Inner bar" } };
for (var i = 0; i < 100; i++)
InnerObjectList.Add(new SomeInnerObject { InnerName = $"Inner bar{i}" });
EditContext = new EditContext(FakeObject).AddDataAnnotationsValidation();
StateHasChanged();
}
}
}
enter image description here
您如何使用数据库中的记录填充组件,在 Controller 中调用 api,如下所示:
private async Task<IEnumerable<Persona>> BuscarPersonas(string searchText)
{
var responseHttp = await repositorio.Get<List<Persona>>($"api/Personas/buscar/{searchText}");
return responseHttp.Response;
}
}

最佳答案

Test of result


enter image description here
这是 Blazor(客户端)和 WebAPI(服务器)的示例。

Client Side(Blazor)


1.绑定(bind)List<Persona>Select2并从 PersonaService 获取数据. Index.razor 的代码
@page "/"
@using System.Linq
@using Demo.WebAssembly.Models
@using Demo.WebAssembly.Data


@inject PersonaService service

<span>Simple string example</span>
<Select2 TItem="Persona"
Id="simple-string-example"
Data="@personas"
TextExpression="@(item => item.Name)"
@bind-Value="@ValueSelected">
</Select2>

<span>Currently selected Inner value: @(ValueSelected?.Name)</span>


<br />

@code
{

private Persona ValueSelected { get; set; } = new Persona { Name = "Name" };

private List<Persona> personas { get; set; }

protected override async Task OnInitializedAsync()
{
var personaList = await service.BuscarPersonas("user");

personas = personaList.ToList();

}


protected override void OnAfterRender(bool firstRender)
{
base.OnAfterRender(firstRender);
if (firstRender)
{

StateHasChanged();
}
}
}

2.从url请求数据("https://localhost:44307/api/Personas/buscar/{searchText}")
PersonaService 的代码
public class PersonaService
{

public async Task<IEnumerable<Persona>> BuscarPersonas(string searchText)
{
HttpClient httpClient = new HttpClient();
var response = await httpClient.GetAsync("https://localhost:44307/api/Personas/buscar/" + searchText);
if (response.IsSuccessStatusCode)
{
var result = await JsonSerializer.DeserializeAsync<Persona[]>(await response.Content.ReadAsStreamAsync(), new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });
return result;
}
else
{
return null; //handle the response that was not successful here.
}
}

}

Server Side(WebAPI)


1. 接收并处理请求。返回 json 中的数据格式。
Controller 的代码
    [HttpGet]
[Route("/api/Personas/buscar/{searchText}")]
public async Task<JsonResult> GetPersona(string searchText)
{
var personas = _repository.getPersona(searchText);

return new JsonResult(personas);
}
2. 从数据库中检索数据。 Repository 的代码
    public List<Persona> getPersona(string searchText)
{
var personas = _context.Personas.Where(p=>p.Name.Contains(searchText)).ToList();

return personas;
}

注意:如果像上例一样从其他域(h​​ttps://localhost:44379)访问数据,不要忘记启用 CORS .

链接: Create a web API with ASP.NET Core

关于c# - 如何在 blazor 中使用 select2 组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63584463/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com