Search code examples
asp.netasp.net-mvcmaster-pagesviewdata

asp.net mvc and ViewData in MasterPage


In order to avoid having to pass Data that goes in the master page of my site before every view in every controller I have created an ApplicationController that sets the data on its constructor... the problem with this approach is that one of the viewdatas I must pass is the URL of the profile Image of the current logged in user.

[Authorize(Roles = "Administrator")]
    public abstract class AdministratorController : Controller
    {
        private IPortalAdministratorServices _servicioPortalAdministrator;
        public AdministratorController()
        {
            _servicioPortalAdministrator = new PortalAdministratorServices();
            ViewData["associates"] = _servicioPortalAdministrator.getAssociates();
            ViewData["picture"] = _servicioPortalAdministrator.GetPic();        

        public AdministratorController(IPortalAdministratorServices service)
        {
            _servicioPortalAdministrator = service;
            }

    }

and so my companies Controllers which inherits from AdministratorController now doesn't have to set all that Data upon every View Call.

[Authorize(Roles = "Administrator")]
public class CompaniesController : AdministratorController
{
    private ICompaniasServices _service;

    public CompaniesController()
    {
        _service = new CompaniasServices(new ModelStateWrapper(this.ModelState));

    }

    public CompaniesController(ICompaniasServices service)
    {
        _service = service;
    }

The problem is this:

When I try to manually access the Companies Controller without actually being logged in the method GetPic() won't actually be able to get the picture URL cause no one is logged in.. and these method is getting called in spite of the Authorize attribute....so now, even after being logged in the ViewData for the picture URL has been permanently set to "unknown.png"

Some of this code isn't mine.. I just discovered the bug but can't figure out how to fix it.


Solution

  • if (User.Identity.IsAuthenticated){
       ViewData["picture"] = _servicioPortalAdministrator.GetPic(); 
    }
    else{
       ...
    }
    

    Is this something u can use?