Finding very little information on how to implement Profiles in Asp.Net MVC, I thought I'd share my solution to implement this.
For demonstration purposes, let's assume you want to store a user's First and Last Name only.
Firstly I created a "UserProfile" class that derive from "System.Web.Profile.ProfileBase" and implemented it as follows:
public class UserProfile : ProfileBase
{
[SettingsAllowAnonymous(false)]
public string FirstName
{
get { return base["FirstName"] as string; }
set { base["FirstName"] = value; }
}
[SettingsAllowAnonymous(false)]
public string LastName
{
get { return base["LastName"] as string; }
set { base["LastName"] = value; }
}
public static UserProfile GetUserProfile(string username)
{
return Create(username) as UserProfile;
}
public static UserProfile GetUserProfile()
{
return Create(Membership.GetUser().UserName) as UserProfile;
}
}
That being done, I ensure my Profile Provider have been set up properly in my web.config (note how I inherit from the above class)
<profile inherits="Krok.Core.BusinessLogic.Models.Account.UserProfile">
<providers>
<clear/>
<add name="AspNetSqlProfileProvider"
type="System.Web.Profile.SqlProfileProvider"
connectionStringName="ApplicationServices" applicationName="/" />
</providers>
</profile>
As I like to keep logic seperated, and also only use strongly typed view models, I created a view model class seperately:
public class UserProfileViewModel
{
[DisplayName("First Name")]
[DataType(DataType.Text)]
public string FirstName { get; set; }
[DisplayName("Last Name")]
[DataType(DataType.Text)]
public string LastName { get; set; }
}
Now, I created two action methods, one for displaying a user's profile, one for editing it:
[Authorize]
public ViewResult Profile()
{
UserProfile profile = UserProfile.GetUserProfile(User.Identity.Name);
var model = new UserProfileViewModel
{
FirstName = profile.FirstName,
LastName = profile.LastName
};
return View(model);
}
[HttpPost]
[Authorize]
public ActionResult Profile(UserProfileViewModel model)
{
if (ModelState.IsValid)
{
UserProfile profile = UserProfile.GetUserProfile(User.Identity.Name);
profile.FirstName = model.FirstName;
profile.LastName = model.LastName;
profile.Save();
return RedirectToRoute("Account.Profile");
}
return View(model);
}
Now, you obviously just will create two views, both strongly typed (UserProfileViewModel)
Hope this help for anyone that need to implement Profiles in a Asp.Net MVC application.
The ASP.NET Wiki was started by Scott Hanselman in February of 2008. The idea is that folks spend a lot of time trolling the blogs, googlinglive-searching for answers to common "How To" questions. There's piles of fantastic community-created and MSFT-created content out there, but if it's not found by a search engine and the right combination of keywords, it's often lost.
The ASP.NET Wiki articles moved to CodeProject in October 2013 and will live on, loved, protected and updated by the community.