Ok, I looked on StackOverflow and google and didn't found any solution.What I read on web is that calling a Controller from a Razor page is BAD and it said we need to rethink our programming (as stated on Calling controller action method directly from Razor View)
Fine, I accept that. But I didn't find any other ways. Here the problem:
- I got a .NET8 Web App Blazor/Razor (NOT WASM) with Microsoft Identity (Render is Server, Interactivity per page)
- The same Web App also have API Controllers
- One of theses controller can querying the Db for a webLink (stored) based on a stringId.
- Example: StringId is E4A1 and it represent: https://Google.ca/
- When querying the Api for "E4A1", it return "https://Google.ca/"
- Querying the Controller (API) work fine, I need to be able to Query from a Razor page.
Here what I tried.
- From Razor page, I added:
@inject ApplicationDbContext _DbContext- [Link] Model looks like this
public class LinkModel { [Key] public int Id { get; set; } [Required] [MaxLength(8)] public string StringId { get; set; } = ""; [MaxLength(512)] public string Url { get; set; } = "";}- From Razor page @code section, I have a function trying to call
string strId = "E4A1";LinkModel? objTable = await _DbContext.DbLinks.FirstOrDefaultAsync(w => w.StringId == strId);Visual Studio complains that FirstOrDefaultAsync DOES NOT EXIST in that context.
So what I did is, inside the LinkController, I created a function:
public static class LinkFunctions { public static async Task<string> GetUrlX(ApplicationDbContext objDbContext, string strHex32Id) { LinkModel? objTable = await objDbContext.DbLinks.FirstOrDefaultAsync(w => w.StringId == strHex32Id); return objTable.Url; }}This is the exact same code but in the Controller
and I call it from my Razor page like this:
string strId = "E4A1";string strUrl = await LinkFunctions.GetUrlX(_DbContext, strId);which works...
Here the questions:
- Why it isn't working from the Razor page (same code) ?
- Why is it bad to call the controller from the Razor page
- How do I fix it in a better way ?