ASP.Net MVC 3 Sending string from HTTP-POST Method

2019-09-06 00:02发布

问题:

I am trying to adapt the AccountController class so that it uses my own backend database. In order to do this completely I need to send a string to the _Layout.cshtml to be checked. How is this possible?

I have tried with ViewData but this requires the Controller to correspond to the view attached e.g. AccountController to View/Account/LogOn.cshtml will work.

I believe that ViewBag works in the same way as I am getting a null reference when I try to access it in the _Layout.cshtml.

At the moment my code is a bit damaged due to trying to fix the problem but here is what I have. Hopefully it will help to explain better.

AccountController/[HTTP-POST] LogOn

...
if (user.GetRole(model.UserName).Equals("Admin"))
{
     ViewBag.Role = "Admin";
}
...

_Layout.cshtml

@if (Request.IsAuthenticated && ViewBag.Role.Equals("Admin"))
{
   ...
}

I no longer think this can be done with ViewBag or ViewData (Due to comments). Any solution would be welcome.

Thank you in advance - Ankou

回答1:

Change your code to

if (user.GetRole(model.UserName).Equals("Admin"))
{
    ViewBag.Role = "Admin";
}
else{
    ViewBag.Role = "";
}

You will get an error of ViewBag.Role does not exist. So it must always be set.

Edits

From your comments, I think you might be best creating a Child Action which has it's own controller and does the work for you.

@Html.RenderAction("LogonDisplay");

This will check the Roles, set the ViewBag values, and then display as needed.



回答2:

You may be using the _Layout before you call Logon action. Therefore, put a check on your _Layout.

@if (Request.IsAuthenticated && ViewBag.Role != null && ViewBag.Role.Equals("Admin"))
{
   ...
}