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.
A minimal example(I don't know your
Userclass,so just tried with WeatherForecast class in default template):in RazorComponent:
Create a js file(myjs.js) under wwwroot folder and add the jquery codes:
add the required js file in _Host.cshtml:
Api endpoint:
Now the result:
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