Jasiel Torres
Jasiel Torres

Reputation: 427

How to use select2 component in blazor?

hello community I am trying to use the select2 component in blazor, I took an example from github but the truth is I am lost in how to fill the component with the records from the database

this is the razor page and this is the component:

<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

How could you fill the component with records from the database, calling an api in a controller, something like this:

private async Task<IEnumerable<Persona>> BuscarPersonas(string searchText)
    {
        var responseHttp = await repositorio.Get<List<Persona>>($"api/Personas/buscar/{searchText}");
        return responseHttp.Response;
    }
}

Upvotes: 3

Views: 7759

Answers (1)

Michael Wang
Michael Wang

Reputation: 4022

Test of result

enter image description here

Here is example of Blazor(client) and WebAPI(server).

Client Side(Blazor)

1. Bind List<Persona> to Select2 and fetch data from PersonaService.

Codes of 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. Request data from url("https://localhost:44307/api/Personas/buscar/{searchText}")

Codes of 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. receive and handle the request. return data in json format.

Codes of Controller

    [HttpGet]
    [Route("/api/Personas/buscar/{searchText}")]
    public async Task<JsonResult> GetPersona(string searchText)
    {
        var personas = _repository.getPersona(searchText);

        return new JsonResult(personas);
    }

2. Retrieve Data From Database.

Codes of Repository

    public List<Persona> getPersona(string searchText)
    {
        var personas = _context.Personas.Where(p=>p.Name.Contains(searchText)).ToList(); 

        return personas;
    }



Notes: If access data from other domain(https://localhost:44379) like the example above, don't forget to enable CORS.



Links: Create a web API with ASP.NET Core

Upvotes: 3

Related Questions