How do I maintain a ViewBag for all Controllers?

5

I'm developing on ASPNET MVC 4 with Razor.

I made the login page and everything is ok.

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

As I'm doing a redirect, then I'm doing this in Action LogOn:

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

There in VIEW / Home / Index, I have this code:

ViewBag.user = ViewBag.usuario;

And then the user name is being shown successfully.

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

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

    
asked by anonymous 19.09.2014 / 00:22

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 dial the Controller :

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

More information? Read here .

    
19.09.2014 / 07:05