Search code examples
c#asp.netasp.net-corerazor-pages

Access razor page Model from parent abstract page


I have a base abstract class for my razor pages like this:

public abstract class NGBaseRazorPage : Page
{
    protected NGBaseRazorPage()
    {

    }

    public Guid PageId { get; } = Guid.NewGuid();
}

and I have a base PageModel like this:

public abstract class NGBasePageModel : PageModel
{
    [BindProperty]
    public Guid PageId { get; }
}

Now I want to access the PageModel from NGBaseRazorPage on a razor page that inherited from NGBaseRazorPage like this.

@page "/TestPage"
@inherits NGBaseRazorPage
@model SomeAwesomePageModel // Already inherrited from NGBasePageModel.
{
}

FYI: My project type is ASP .NET Core and it is based on .NET 7.0. Also, I shared a minimal respos to demonstrate what I want here on Github

GitHub Repository

Thank you.


Solution

  • Try to add the below code in the form in Index to pass the PageId to post method:

    <input name="PageId" type="hidden" value="@PageId"  />
    

    The full form like:

    <form method="post">
    
        <div>
            <label>This is the page id</label>
            <br />
            <label type="text">@PageId</label>
        </div>
        <input name="PageId" type="hidden" value="@PageId"  />
    
        <div>
            <button type="submit">Post</button>
        </div>
    
    </form>
    

    result:

    enter image description here