Search code examples
asp.net-coreconditional-statementsrazor-pages

Change asp-page attribute value based on condition in razor pages


When a click on a link the pages should be displayed on userroles.Say for example if the userrole is superadmin,then the user will have access to PageA.If the userrole is admin,then the user will have access to PageB. What i tried is ,

@if (Context.Session.GetString("userrole") == "superadmin")
                {
                    var HomepageUrl = "/PageA";
                }
                else
                {
                    var HomepageUrl = "/PageB";
                }
                <a asp-area="" asp-page="@HomepageUrl"></a>

But im getting error like "HomepageUrl doesnot exist in the current context". Any help would be appreciated.


Solution

  • You can try to use the conditional operator ?:,here is an official doc,here is a demo:

    <a asp-area="" asp-page="@(Context.Session.GetString("userrole") == "superadmin"?"/PageA":"/PageB")">link</a>