2020年11月13日 星期五

Blazor 學習心得

實作篩選方塊

html
<input type="text" @bind="filter"   @bind:event="oninput"> <= 若要隨時輸入資料立刻篩選則改變預設事件onchange 為 oninput,否則失去焦點才會改變 filter 
@foreach (var forecast in forecasts)
            {
                <tr>
                    <td>@forecast.Date.ToShortDateString()</td>
                    <td>@forecast.TemperatureC</td>
                    <td>@forecast.TemperatureF</td>
                    <td>@forecast.Summary</td>
                </tr>
            }

c#
private IEnumerable<WeatherForecast> forecasts => forecastss.Where(a => filter!=default && a.Summary.Contains( filter) || filter == default || filter == "");

呼叫 javascript 函數

html
@inject IJSRuntime JS;
<script>
        window.Alert = function (message) {
            alert(message);
        }
</script>

c#
await JS.InvokeVoidAsync("Alert", "123");

存取資料庫

startup.cs
public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContextFactory<xxxContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("xxx")));

xxxContext.cs
刪除空參數建構者避免出錯

設定元件
@implements IDisposable
@inject Microsoft.EntityFrameworkCore.IDbContextFactory<xxxContext> DbFactory

產生DbContext
xxxContext db;
protected override async Task OnInitializedAsync()
    {
        db = DbFactory.CreateDbContext();
        await base.OnInitializedAsync();
    }

釋放DbContext
public void Dispose()
    {
        db.Dispose();
    }


沒有留言:

自訂權限驗證機制

// 使用 filter [Route("api/[controller]")] [ApiController] [Authorize] [TypeFilter(typeof(CustomAsyncAuthorizationFilter))] public c...