How to display list of staff using JS Interop in Blazor Server?

157 Views Asked by At

Good day everyone.

I am currently working on my project in Blazor Server. I have a stored procedure named "getUser" joing two table(User and UserContact) in my SSMS and I am using JQuery ajax and I want to display the list of users(stored procedure) when clicking the NavMenu. But I encountered an error : status 500 after OnInitializedAsync.

Here's my code below.

//c# code

 protected override async Task OnInitializedAsync()
  {
      await JSRuntime.InvokeVoidAsync("getCStaffInfo");
  }

//javascript function

window.getCStaffInfo = function () {
    debugger;

    $.ajax({
        url: '/api/user',
        method: 'GET',
        succes: function (data) {
            debugger
            console.log(data);
        }
    });
}

//controller

[Route("api/[controller]")]
[ApiController]
public class UserController: ControllerBase
{
    private readonly SampleUserDbContext _context;

    public UserController(SampleUserDbContext context)
    {
        _context = context;
    }

    [HttpGet]
    public async Task<ActionResult<IEnumerable<User>>> GetCStaffInfo()
    {
        // Execute the stored procedure and return the results
        var user = await _context.User.FromSqlRaw("EXECUTE getCstaffInfo").ToListAsync();

        return user;
    }
}

//Program.cs

 app.UseMapControllers(); 

Note: I also tried fetching using services but still same error occurred.

1

There are 1 best solutions below

1
Ruikai Feng On BEST ANSWER

A minimal example(I don't know your User class,so just tried with WeatherForecast class in default template):

in RazorComponent:

@inject  IJSRuntime JS

<table class="table">
    <thead>
        <tr>
            <th>Date</th>
            <th>Temp. (C)</th>                
            <th>Summary</th>
        </tr>
    </thead>
</table>




@code{
    
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        await base.OnAfterRenderAsync(firstRender);
        await JS.InvokeVoidAsync("ShowWeatherForecast");
    }
}

Create a js file(myjs.js) under wwwroot folder and add the jquery codes:

window.ShowWeatherForecast = function () {   
    
    $.ajax({
        url: '/api/weatherforecast',
        method: 'GET',        
        success: function (data) {
            console.log(data)
            var tbody = $("<tbody></tbody>")
            for (i = 0; i < data.length; i++)
            {
                var tr = $("<tr></tr>")
                var td1 = $("<td></td>") 
                
                td1.append(data[i].date)
                var td2 = $("<td></td>")
                td2.append(data[i].temperatureC)
                var td3 = $("<td></td>")
                td3.append(data[i].summary)
               
                tr.append(td1,td2,td3)
                tbody.append(tr)

            }
            $('table').append(tbody); 
        }
    });
}

add the required js file in _Host.cshtml:

<script src="_framework/blazor.server.js"></script>
    <script src="lib/jquery/jquery.min.js"></script>
    <script src="js/MyJs.js"></script>

Api endpoint:

[Route("api/[controller]")]
    [ApiController]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
         };
        public IActionResult GetForecastAsync()
        {
            var weatherforecasts=Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateOnly.FromDateTime(DateTime.Now).AddDays(index),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)]
            }).ToArray();
            //notice you have to return object result with 200 statue code to hit success call-back in ajax
            return Ok(weatherforecasts);
        }
    }

Now the result: enter image description here

Although it could work,I don't think it's a good solution,usually we call api endpoint with httpclient ,you could follow this document