본문 바로가기
Blazor

Blazor WASM] REST API, DropDownList onchange 데이터 연동

by Fastlane 2021. 9. 16.
728x90
반응형

소스링크 : https://github.com/BigExecution/BlazorWASM.git

 

Blazor WASM] REST API, API로 리스트 가져와서 뿌려주기

소스링크 : https://github.com/BigExecution/BlazorWASM.git open api를 호출해서 대학정보를 가져와 리스트로 뿌려주자 1. 우선 Model을 만들자. Models 폴더를 추가 -> University class를 추가한다. 2. 그..

bigexecution.tistory.com

에 이어서 상단에 DropDownList를 추가해서 onchange시 데이터를 다시 가져와서 뿌려주자. 

 

1. UniversityData.razor 페이지 상단에 DropDownList를 추가하고, onchange 이벤트 핸들러를 처리한다. 

@using TEST.Models;
@using TEST.Services;
@page "/universitydata";

<h1>Universities of Korea</h1>

<p>This component demonstrates fetching data from the server.</p>
<select id="country" @onchange="@(e => GetUniversitiesByCountry(e))">
    <option>Country</option>
    <option value="Korea,+Republic+of">Korea, Republic of</option>
    <option value="China">China</option>
    <option value="Japan">Japan</option>
</select>

@if (universities == null)
{
    <p><em>Loading...</em></p>
}
else
{
    <table class="table">
        <thead>
            <tr>
                <th>Name</th>
                <th>Country</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var university in universities.ToList())
            {
                <tr>
                    <td>@university.name</td>
                    <td>@university.country</td>
                </tr>
            }
        </tbody>
    </table>
}

@code {


    protected IEnumerable<University> universities;

    [Inject]
    protected IUniversityService UniversityService { get; set; }


    protected override async Task OnInitializedAsync()
    {
        //universities = await UniversityService.GetUniversities();
    }

    protected async Task GetUniversitiesByCountry(ChangeEventArgs e)
    {
        string country = e.Value.ToString();
        if (!string.IsNullOrEmpty(country)) {
            universities = await UniversityService.GetUniversities(country);
        }
    }
}

2. API 호출시 country를 파리미터로 받아 처리한다. 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using TEST.Models;

namespace TEST.Services
{
    public class UniversityService : BaseService, IUniversityService
    {
        public UniversityService(HttpClient httpClient) : base(httpClient) { }

        public async Task<IEnumerable<University>> GetUniversities(string country)
        {
            //return await GetMethodList<University>($"/search?country=Korea,+Republic+of");
            return await GetMethodList<University>($"/search?country={country}");
        }
    }
}

3. DropDownList onchange 마다 데이터가 바뀌는 것을 확인할 수 있다. 

 

728x90
반응형

댓글