Click here to Skip to main content
15,881,655 members
Articles / Web Development / HTML

ASP.NET MVC 5: Building Your First Web Application - Part 4

Rate me:
Please Sign up or sign in to vote.
4.73/5 (9 votes)
5 Aug 2016CPOL4 min read 24.9K   760   10   7
This is part four of the series on Building Web Applications in ASP.NET MVC 5.

Introduction

Just to give you a quick recap, In Part 1, I’ve demonstrated how to create a simple database from scratch, talked about a brief overview of ASP.NET MVC in general, demonstrated how to build a simple data access using the Entity Framework 6, and created a simple implementation of a Signup page in MVC. Part 2 of the series talked about the step-by-step process of creating a basic login page and creating a simple role-based page authorization within the MVC application. Part 3 of the series talked about how to do Fetch, Edit, Update and Delete (FEUD) operations in the application using jQuery and jQuery AJAX.

If you haven't gone through my previous articles, please refer to the following links below:

In this article, we will create a page to allow users to modify their profile data.

Let’s Get Started!

Adding the GetUserProfile() Method

To begin with, open “UserManager” class and add the following method below:

C#
public UserProfileView GetUserProfile(int userID) {  
            UserProfileView UPV = new UserProfileView();  
            using (DemoDBEntities db = new DemoDBEntities()) {  
                var user = db.SYSUsers.Find(userID);  
                if (user != null) {  
                    UPV.SYSUserID = user.SYSUserID;  
                    UPV.LoginName = user.LoginName;  
                    UPV.Password = user.PasswordEncryptedText;  
  
                    var SUP = db.SYSUserProfiles.Find(userID);  
                    if (SUP != null) {  
                        UPV.FirstName = SUP.FirstName;  
                        UPV.LastName = SUP.LastName;  
                        UPV.Gender = SUP.Gender;  
                    }  
  
                    var SUR = db.SYSUserRoles.Find(userID);  
                    if (SUR != null) {  
                        UPV.LOOKUPRoleID = SUR.LOOKUPRoleID;  
                        UPV.RoleName = SUR.LOOKUPRole.RoleName;  
                        UPV.IsRoleActive = SUR.IsActive;  
                    }  
                }  
            }  

            return UPV;  
}  

The method above gets the specific user information from the database by passing the SYSUserID as a parameter. You may have noticed that the method returns a UserProfileView type which holds some properties from different tables. 

Adding the EditProfile() Action Method

Now, open “HomeController” class and add the following action methods:

C#
[Authorize]
public ActionResult EditProfile()
{
    string loginName = User.Identity.Name;
    UserManager UM = new UserManager();
    UserProfileView UPV = UM.GetUserProfile(UM.GetUserID(loginName));
    return View(UPV);
}


[HttpPost]
[Authorize]
public ActionResult EditProfile(UserProfileView profile)
{
    if (ModelState.IsValid)
    {
        UserManager UM = new UserManager();
        UM.UpdateUserAccount(profile);

        ViewBag.Status = "Update Sucessful!";
    }
    return View(profile);
}

The code above, is composed of two action methods. The first EditProfile() method will be invoked, once the page is requested and loaded to the browser. What it does is to get the user profile data by calling the GetUserProfile() method by passing the SYSUserID as the parameter. The second is the overload method which will be invoked during POST request, that is when you hit the Button to save the data. What it does is that it first checks for validity of the fields (if they are valid and not empty), then calls the method UpdateUserAccount() and passes the UserProfileView model from the View to that method. If you still remember from my previous article series, the UpdateUserAccount() method is where it executes the actual saving of data to our database.

You may also have noticed that both action methods are decorated with the [Authorize] attribute to ensure that both methods will only be accessible by authenticated users regardless of roles.

Adding the EditProfile View

The next step is to generate the View for the profile page. To do this, right click on the EditProfile() method and select “Add View”. In the Add View dialog, supply the needed fields as shown in the figure below:

Image 1

Figure 1: Add View Dialog

Take note of the Model class field value. It should be “UserProfileView”. Now, click Add to scaffold the UI for you.

Visual Studio will generate all the controls in the View, based on the fields you defined from your Model (UserProfileView). This means that it will also generate unnecessary fields that we don’t want to edit, such as, the LOOKUPRoleID and IsRoleActive. Besides that, we will also need to provide a drop-down list for displaying the Gender field. So, make sure to update the generated HTML markup. It would look similar to the following:

Razor
@model MVC5RealWorld.Models.ViewModel.UserProfileView  
  
@{  
    ViewBag.Title = "EditProfile";  
    Layout = "~/Views/Shared/_Layout.cshtml";  
}  
  
<h2>Edit Your Profile</h2>  
  
@using (Html.BeginForm())  
{  
    @Html.AntiForgeryToken()  
      
    <div class="form-horizontal">  
        <hr />  
        <span class="alert-success">@ViewBag.Status</span>  
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })  
        @Html.HiddenFor(model => model.SYSUserID)  
  
        <div class="form-group">  
            @Html.LabelFor(model => model.RoleName, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.DisplayFor(model => model.RoleName)  
                @Html.ValidationMessageFor(model => model.RoleName, "", new { @class = "text-danger" })  
            </div>  
        </div>  
  
        <div class="form-group">  
            @Html.LabelFor(model => model.LoginName, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.LoginName, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.LoginName, "", new { @class = "text-danger" })  
            </div>  
        </div>  
  
        <div class="form-group">  
            @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })  
            </div>  
        </div>  
  
        <div class="form-group">  
            @Html.LabelFor(model => model.FirstName, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.FirstName, "", new { @class = "text-danger" })  
            </div>  
        </div>  
  
        <div class="form-group">  
            @Html.LabelFor(model => model.LastName, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })  
            </div>  
        </div>  
  
        <div class="form-group">  
            @Html.LabelFor(model => model.Gender, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.DropDownListFor(model => model.Gender, new List<SelectListItem> {  
                    new SelectListItem { Text="Male", Value="M" },  
                    new SelectListItem { Text="Female", Value="F" }  
                }, new { @class = "form-control" })  
            </div>  
        </div>  
  
        <div class="form-group">  
            <div class="col-md-offset-2 col-md-10">  
                <input type="submit" value="Save" class="btn btn-default" />  
            </div>  
        </div>  
    </div>  
}  
  
<div>  
    @Html.ActionLink("Back", "Welcome")  
</div>

The markup above is a strongly-typed View which renders HTML based on the UserProfileView model. Now, add the following markup in the “Welcome.cshtml” view.

Razor
@Html.ActionLink("Edit Profile", "EditProfile", "Home")

The markup, above, is nothing but a link to the EditProfile page, so that when you log in, you can easily navigate to your profile page and start modifying data.

Testing the Application

Now, try to build your code and run your application. The output should look similar to the figure below:

Image 2

Figure 2: Edit User Page

After modifying the data

Image 3Figure 3: After Successful Update

That's it! I hope someone find this article useful. Just in case you want to test your MVC 5 app to run on IIS, then you can refer this step-by-step article about: Deploying your ASP.NET MVC 5 App to IIS8

Summary

There's not much feature we've seen in this part of the series, but we've learned to create a very basic profile page to let users modify their information in MVC 5 app.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
United States United States
A code monkey who loves to drink beer, play guitar and listen to music.

My Tech Blog: https://vmsdurano.com/
My Youtube Channel: https://www.youtube.com/channel/UCuabaYm8QH4b1MAclaRp-3Q

I currently work as a Solutions Architect and we build "cool things" to help people improve their health.

With over 14 years of professional experience working as a Sr. Software Engineer specializing mainly on Web and Mobile apps using Microsoft technologies. My exploration into programming began at the age of 15;Turbo PASCAL, C, C++, JAVA, VB6, Action Scripts and a variety of other equally obscure acronyms, mainly as a hobby. After several detours, I am here today on the VB.NET to C# channel. I have worked on Web Apps + Client-side technologies + Mobile Apps + Micro-services + REST APIs + Event Communication + Databases + Cloud + Containers , which go together like coffee crumble ice cream.

I have been awarded Microsoft MVP each year since 2009, awarded C# Corner MVP for 2015, 2016,2017 and 2018, CodeProject MVP, MVA, MVE, Microsoft Influencer, Dzone MVB, Microsoft ASP.NET Site Hall of Famer with All-Star level and a regular contributor at various technical community websites such as CSharpCorner, CodeProject, ASP.NET and TechNet.

Books written:
" Book: Understanding Game Application Development with Xamarin.Forms and ASP.NET
" Book (Technical Reviewer): ASP.NET Core and Angular 2
" EBook: Dockerizing ASP.NET Core and Blazor Applications on Mac
" EBook: ASP.NET MVC 5- A Beginner's Guide
" EBook: ASP.NET GridView Control Pocket Guide

Comments and Discussions

 
BugFind works with only primary key - Posted the correct code Pin
Member 136156987-Nov-19 1:16
Member 136156987-Nov-19 1:16 
Bugin the UserManager.cs, I get "syntax error, expected ':'", Pin
Member 135576724-Dec-17 10:11
Member 135576724-Dec-17 10:11 
GeneralRe: in the UserManager.cs, I get "syntax error, expected ':'", Pin
Vincent Maverick Durano4-Dec-17 15:48
professionalVincent Maverick Durano4-Dec-17 15:48 
GeneralMaster Detail Views Pin
Faisal Bora21-Aug-16 17:43
Faisal Bora21-Aug-16 17:43 
GeneralRe: Master Detail Views Pin
Vincent Maverick Durano1-Dec-16 22:58
professionalVincent Maverick Durano1-Dec-16 22:58 
QuestionQuestion on Scaffolding Pin
Ken Kazinski13-Aug-16 5:13
professionalKen Kazinski13-Aug-16 5:13 
AnswerRe: Question on Scaffolding Pin
Vincent Maverick Durano15-Aug-16 0:19
professionalVincent Maverick Durano15-Aug-16 0:19 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.