This demo is a continuation of my previous article about "Creating a Simple Log-in Form". Basically in this post I'm going to demonstrate the basic on how to edit and update the form with ASP.NET MVC 3.
Before you go any further, I'd suggest you to check out my previous article first about "ASP.NET MVC 3: Creating a Simple Sign-Up Form" and "Creating a Simple Log-in Form".
STEP 1: Creating the Model class
Just for the simplicity of this demo, I'm just going to display the FirstName, LastName and ContactNumber in the form and have the user edit those information as they like. So first we'll add a new class under ViewModel's folder. To do this just right click on the "ViewModels" folder and then select Add -> then select class. In this example I'm going to name the class as "UserProfile" with the following properties below:
using System.ComponentModel.DataAnnotations;
namespace MVCDemo.Models.ViewModels
{
public class UserProfile
{
[Display(Name = "User Login ID")]
public string UserLoginID { get; set; }
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Display(Name = "Contact Number")]
public string ContactNumber { get; set; }
}
}
As you can see there's nothing really fancy in the code above. It just contains four properties with the Display attribute decorated on each property.
STEP 2: Creating the View
The next step is to create a view under "Account" folder. To do this just right click on the folder -> select Add -> and then select View. A popup window should appear wherein you can type in the view name.
In this demo I'm just going to name the view as "MyProfile". Now select Razor (CSHTML) as the View engine then check the Create a strongly-type view checkbox. Under the model class drop down, select UserProfile class. Then under scaffold template select Edit. Click Add to generate the view and the pre-defined codes for you. Here's the code below with few modifications:
@model MVCDemo.Models.ViewModels.UserProfile
@{
ViewBag.Title = "My Profile";
}
<h2>ViewPage1</h2>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>User Profile</legend>
<br />
<div style="color:Green">@ViewData["Status"]</div>
<br />
<div class="editor-label">
@Html.LabelFor(model => model.FirstName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.FirstName)
@Html.ValidationMessageFor(model => model.FirstName)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.LastName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.LastName)
@Html.ValidationMessageFor(model => model.LastName)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.ContactNumber)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.ContactNumber)
@Html.ValidationMessageFor(model => model.ContactNumber)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Logout", "LogOff", "Account")
</div>
STEP 3: Adding the GetUserDetail() and the UpdateUserProfile() method in the UserManager class
Here's the code below:
public SysUser GetUserDetail(string loginID) {
var userDetails = from p in dre.SysUsers
where p.SysUserLoginID == loginID
select p;
return userDetails.ToList().FirstOrDefault();
}
The code above gets the details of the user information from the database by passing in the loginID as the parameter to the query using LINQ syntax.
public void UpdateUserProfile(UserProfile userProfile) {
var user = (from p in dre.SysUsers
where p.SysUserLoginID == userProfile.UserLoginID
select p).FirstOrDefault();
user.FirstName = userProfile.FirstName;
user.LastName = userProfile.LastName;
user.ContactNumber = userProfile.ContactNumber;
dre.SaveChanges();
}
The method above takes UserProfile object as the parameter. It then query the database to get the specific user details based on the UserLoginID. It will then update the fields by assigning the new values from the UserProfile object and then save the changes. The UserProfile object is the object used in our strongly typed view "MyProfile".
STEP 4: Adding the MyProfile action methods in the AccountController()
Here's the block of code below:
[Authorize]
public ActionResult MyProfile(string userLoginID) {
UserManager um = new UserManager();
var userDetail = um.GetUserDetail(userLoginID);
UserProfile user = new UserProfile();
user.UserLoginID = userDetail.SysUserLoginID;
user.FirstName = userDetail.FirstName;
user.LastName = userDetail.LastName;
user.ContactNumber = userDetail.ContactNumber;
return View(user);
}
What it does is it creates an instance of the UserManager class and then get the user details data by calling the GetUserDetail() method with the parameter from the UserManager object. We then populate the properties we defined in the UserProfile class that we have created in STEP 1 so that the View that we have created in STEP 2 will be populated with the result.
[HttpPost]
[Authorize]
public ActionResult MyProfile(UserProfile userProfile) {
UserManager um = new UserManager();9:34 PM 1/9/2012
um.UpdateUserProfile(userProfile);
ViewData["Status"] = "Update Sucessful!";
return View(userProfile);
}
The method above is reponsible for saving the information to the database. This method will be called upon clicking the "Save" button. As you can see the method is decorated with [HttpPost] which means that the method can only be invoked during post request. The first line creates an instance of the UserManager object and the call the UpdateUserProfile method by passing the UserProfile object to it. The UserProfile object contains the updated data from the view and ready to be used to perform the update. We then use ViewData to store some status message to let the user know that the record is updated successfully in the database.
You also noticed that both methods are decorated with the [Authorize] attribute to essure that the method can only be invoked by authenticated users.
STEP 5: Adding a link to Edit Profile
In the Welcome page add the following line below.
@Html.ActionLink("Edit Profile", "MyProfile", "Account", new { userLoginID = Context.User.Identity.Name }, null)
The first parameter sets the text of the link. The second parameter is the Action method (in this case we have the "MyProfile" action method). The third parameter is the controller name in which the action method belongs to (in this case we set the Account for AccountController. The fourth parameter is Route arguments, in this parameter we can pass values to our action method ( in this case we passed in the identity of the user who logged in). The last parameter is the html arguments. We set it to null/nothing so that the correct method will be called.
Here are some screen shots of the output.
After log-in
The MyProfile page
Editing the form
After updating the form
That’s it! I hope someone find this post useful!