How do I maintain a Viewbag for all Controllers?

Asked

Viewed 403 times

5

I am developing in ASPNET MVC 4 with Razor.

I made the login page and everything is ok.

After login, the famous phrase "Welcome FLAVIO" is being successfully returned, via Viewbag.

As I’m doing a redirect, so I’m doing it this way, in Action Logon:

User user = _repository.AutenticarUsuario(f["username"], f["password"]);
TempData["usuario"] = user.fname;
return Redirect("/Home/Index");

At VIEW /Home/Index, I have this code:

ViewBag.user = ViewBag.usuario;

And then the user name is being successfully displayed.

The problem is that if I enter some other link in the system, the user name goes to space!

How do I make the user name persist for all actions?

1 answer

6


Make a ActionFilter:

public class MeuActionFilter : ActionFilterAttribute, IActionFilter
{
    void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
    {
        ViewBag.User = // coloque aqui a informação do usuário

        this.OnActionExecuting(filterContext);
    }
}

Then just mark the Controller:

[MeuActionFilter]
public class MeuController : Controller
{
    ...
}

More information? Read here.

  • 1

    Thank you. This response made me search Actionfilters and I saw that I have many more options, such as registering the value I need globally to avoid that I keep having to add the filter "marker" in each Controller, among other several options.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.