Quantcast
Channel: Active questions tagged blazor - Stack Overflow
Viewing all articles
Browse latest Browse all 4839

Reading database from Razor

$
0
0

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:

  1. I got a .NET8 Web App Blazor/Razor (NOT WASM) with Microsoft Identity (Render is Server, Interactivity per page)
  2. The same Web App also have API Controllers
  3. 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/"
  4. Querying the Controller (API) work fine, I need to be able to Query from a Razor page.

Here what I tried.

  1. From Razor page, I added:
@inject ApplicationDbContext _DbContext
  1. [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; } = "";}
  1. 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:

  1. Why it isn't working from the Razor page (same code) ?
  2. Why is it bad to call the controller from the Razor page
  3. How do I fix it in a better way ?

Viewing all articles
Browse latest Browse all 4839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>