Domanda

I have an MVC4 application and I've been following the Pluralsight video tutorials.

I've got my UserProfile table with an added property and it's working great:

<Table("UserProfile")>
Public Class UserProfile
    <Key>
    <DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)>
    Public Property UserId As Integer
    Public Property UserName As String
    Public Property FullName As String
End Class

UserId and UserName are default, but I've added FullName and got it working. When I create new users their full name is placed in to the FullName field in the database.

How do I access FullName from within a Razor view?

I don't want to use sessions, ViewData or models. In fact I want this displayed on every page so doing this via a controller is not an option.

I was hoping to access it via @Profile.Item("FullName") or @Profile.PropertyValues("FullName") but the Profile object is empty. How do I set it?

Profile object is empty.png

È stato utile?

Soluzione

Check out this post by Phil Haack. Or this one on develoq

You can create a new Base page for your views that has your Profile object as a property.

public abstract class ProfileWebViewPage<T> : System.Web.Mvc.WebViewPage
{
  public UserProfile Profile { get; set; }

  public override void InitHelpers()
  {
    base.InitHelpers();
    //Set your Profile here. 
  }
}

Then set it as the base type in the webconfig (in the views folder):

  <system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="MyProject.ProfileWebViewPage">
      <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" />
      </namespaces>
    </pages>
  </system.web.webPages.razor>

Then you can simply access it by this:

@Profile.FullName

EDIT

Okay, sorry, I thought you had the information and was just looking for a way to access it on your pages.

You can't (AFAIK) access custom profile information with the SimpleMembershipProvider. I think you need to be looking into a custom ProfileProvider (http://dotnetnsqlcorner.blogspot.co.nz/2012/05/implementing-custom-profile-in-aspnet.html) or check out using SqlProfileProvider (Implementing Profile Provider in ASP.NET MVC)

Or:

YOu could just use EF to do the data access to go straight to the profile (using what ever DB context UserProfile is under:

Profile = (new UsersContext()).UserProfiles.SingleOrDefault(u => u.UserName = User.Identity.Name)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top