Search code examples
c#asp.net-mvcasp.net-mvc-4forms-authenticationsimplemembership

How to access Extensions Properties in View in Asp.Net MVC?


I have an MVC 4 project setup using Forms authentication and the SimpleMembershipProvider. In my users table, I have some other properties such as Email, Firstname, Lastname, etc

How do I access the currently logged on user's profile in a Razor view?

I've tried creating a BaseController and then having the other controllers inherit from it, like so.

   public class BaseController : Controller
    {
        public UserProfile CurrentUser;

        protected override void Initialize(RequestContext requestContext)
        {
            base.Initialize(requestContext);

            if (this.HttpContext.User.Identity.IsAuthenticated)
            {
                var context = new UsersContext();
                var user = context.UserProfiles.SingleOrDefault(u => u.UserName == WebSecurity.CurrentUserName);
                CurrentUser = user;
            }
        }
    }

Then in an HtmlExtension method;

public static class HtmlExtensions
    {
        public static UserProfile CurrentUser(this HtmlHelper htmlHelper)
        {
            var controller = htmlHelper.ViewContext.Controller as BaseController;
            if (controller == null)
            {
                throw new Exception("The controller used to render this view doesn't inherit from BaseController");
            }
            return controller.CurrentUser;
        }
    }

However this doesn't work if I try to retrieve the properties of a user, e.g.

@Html.CurrentUser.Firstname

Solution

  • You have to set the namespace of your HtmlExtensions class on the system.web.webPages.razor -> pages -> namespace tags to it be availible on the View, on the web.config file inside the Views folder, for sample:

    <system.web.webPages.razor>
        <!-- other tags -- >
        <pages pageBaseType="System.Web.Mvc.WebViewPage">
          <namespaces>
            <add namespace="System.Web.Mvc" />
            <add namespace="System.Web.Mvc.Ajax" />
            <add namespace="System.Web.Mvc.Html" />
            <add namespace="System.Web.Optimization"/>
            <add namespace="System.Web.Routing" />
            <add namespace="System.Configuration" />
            <add namespace="MyWebApplication.Extensions"/> <!-- this is a custom namespace -->
          </namespaces>
        </pages>
      </system.web.webPages.razor>
    

    I also recommend you use a GlobalFilter to fill the CurrentUser property.