简体   繁体   中英

how to pass information back to a razor page from the pagemodel cs file in .net core

I am wanting to hide certain parts of an cshtml page depending on user.identity.name.

I have application configurations file from which i successfully retrieve user admin info:

Here c# snippet of that code

        public IActionResult OnGet()
    {
        string admin = _context.ApplicConfs.Select(s => s.AppAdmin).FirstOrDefault();
        string badmin = _context.ApplicConfs.Select(s => s.BackAdmin).FirstOrDefault();
        ViewBag.uadmin = admin;
        ViewBag.ubadmin = badmin;
        return ViewBag();
    }

the cshtml code currently does the following:

    @*@if (@User.Identity.Name == (ViewBag.uadmin) ||  @User.Identity.Name == (ViewBag.ubadmin))
{*@

followed by what html is displayed not displayed (conditionally)

Something like this works in .net core MVC but NOT IN .net core razor pages.

How do I pass the admin string above from the c# pagemodel page to the cshtml razor page so that the current @user.identity.name can be compared to the admin string?

Sorry if its a stupid question...

You can try to use ViewData,Here is a demo:

TestHidden.cshtml.cs:

[BindProperty]
        public User User { get; set; }
        public IActionResult OnGet()
        {
            User= new User { Identity = new Identity { Name = "admin" } };
            ViewData["uadmin"] = "admin";
            ViewData["ubadmin"] = "badmin";
            return Page();
        }

classes:

public class User {
        public Identity Identity { get; set; }
    }
    public class Identity
    {
        public string Name { get; set; }
    }

TestHidden.cshtml:

@if (@Model.User.Identity.Name == ViewData["uadmin"] || @Model.User.Identity.Name == ViewData["ubadmin"])
{
    <h1>User.Identity.Name:@Model.User.Identity.Name</h1>
    <h1>ViewData["uadmin"]:@Model.ViewData["uadmin"]</h1>
    <h1>ViewData["ubadmin"]:@Model.ViewData["ubadmin"]</h1>
}

result: 在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM