Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

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

0.00/5 (No votes)
3 Jul 2018 26  
This article is part 1 of the series for building a simple web application in ASP.NET MVC 5.

Introduction

Technologies are constantly evolving and as developer we need to cope up with what’s the latest or at least popular nowadays. As a starter you might find yourself having a hard-time catching up with latest technologies because it will give you more confusion as to what sets of technologies to use and where to start. We know that there are tons of resources out there that you can use as a reference to learn but you still find it hard to connect the dots in the picture. Sometimes you might think of losing the interest to learn and give up.  If you are confused and no idea how to start building a web app from scratch, then this series of article is for you. Here's the current list of the series for this application:

If you want a PDF version of this series, you can grab a copy of the eBook here: ASP.NET MVC 5: A Beginner's Guide 

Background

ASP.NET MVC 5: Building Your First Web Application is targeted to beginners who want to jump on ASP.NET MVC 5 and get their hands dirty with practical example. I've written this article series in such a way that it’s easy to follow and understand by providing step-by-step process on creating a simple web application from scratch down to deploying your app in IIS Web Server.  As you go along and until such time you finished following the series, you will learn how to create a database using SQL Server, learn the concept of ASP.NET MVC and what it is all about, learn Entity Framework using Database-First approach, learn basic jQuery and AJAX, learn to create pages such as Registration, Login, Profile and Admin page where user can modify, add and delete information. You will also learn how to install and deploy your application in IIS Web Server.

Prerequisites

Before you go any further make sure that you have basic knowledge on the following technologies and langauge:

  • SQL Server
  • Visual Studio
  • ASP.NET in general
  • Basic understanding of ASP.NET MVC
  • Entity Framework
  • C#
  • Basics on HTML, CSS and JavaScript/jQuery

Environment and Development Tools

The following are the tools and environment settings that I am using upon building the web app.

  • Windows 8.1
  • IIS8
  • Visual Studio 2015
  • SQL Express 2014

Let's Get Started!

I’ll try to keep this demo as simple as possible so starters can easily follow. By “simple” I mean limit the talking about theories and concepts, but instead jumping directly into the mud and get your hands dirty with code examples.

What you will learn:

  • Creating a database in MS SQL Server
  • Brief overview of ASP.NET MVC
  • Implementing Entity Framework Database-First approach
  • Creating a simple Signup page

Before we start building an MVC application let’s talk about a bit about MVC because it is very important to know how the MVC framework works.

What is ASP.NET MVC?

ASP.NET MVC is part of the ASP.NET framework. The figure below will give you a high level look to where ASP.NET MVC resides within the ASP.NET framework.

Image 1

Figure 1: The ASP.NET technologies

You will see that ASP.NET MVC sits on top of ASP.NET. ASP.NET MVC is a UI framework that enables a clean separation of concerns and gives you full control over your mark-up. 

To make it more clear, here’s how I view the high-level process of MVC:

Image 2

Figure 2: MVC architecture flow

Unlike in ASP.NET WebForms that a request is going directly to a page file (.ASPX),  in MVC when a user request a page it will first talk to the Controller , process data when necessary and returns a Model to the View for the user to see.

What is a Model?

Model is just a class that implements the logic for the application domain data. Often, model objects retrieved and store model state in database.

What is a Controller?

Just like Models, Controller is also a class that handles the user interaction. It will work with the model, and ultimately select a view to render in the browser.

What is a View?

As the name suggests, a View is the component that displays the application’s user interface (UI), typically this UI is created from the model data.

To put them up together, the M is for Model, which is typically where the BO (Business Objects), BL (Business Layer) and DAL (Data Access) will live. Note that in typical layered architecture, your BL and DAL should be in separate project. The V is for View, which is what the user sees. This could simply mean that any UI and client-side related development will live in the View including HTML, CSS and JavaScript. The C is the Controller, which orchestrates the flow of logic. For example if a user clicks a button that points to a specific URL, that request is mapped to a Controller Action method that is responsible for handling any logic required to service the request, and returning a response- typically a new View, or an update to the existing View.

If you are still confused about Model, View and Controller, don’t worry because I will be covering how each of them relates to each other by providing code examples. So keep following.

Creating a Database

Open SQL Server or SQL Server Express Management Studio and then create a database by doing the following:

  • Right click on the Databases folder
  • Select New Database
  • Enter a database name and then click OK. Note that in this demo I used “DemoDB” as my database name.

The “DemoDB” database should be created as shown in the figure below:

Image 3

Figure 3: New database created

Alternatively, you can also write a SQL script to create a database. For example:

CREATE DATABASE DemoDB;

Creating Database Tables

In SQL management server, open a New Query window or just press CTRL + N to launch the query window and then run the following scripts:

LOOKUPRole table

USE [DemoDB]
GO

CREATE TABLE [dbo].[LOOKUPRole](
    [LOOKUPRoleID] [int] IDENTITY(1,1) NOT NULL,
    [RoleName] [varchar](100) DEFAULT '',
    [RoleDescription] [varchar](500) DEFAULT '',
    [RowCreatedSYSUserID] [int] NOT NULL,
    [RowCreatedDateTime] [datetime]  DEFAULT GETDATE(),
    [RowModifiedSYSUserID] [int] NOT NULL,
    [RowModifiedDateTime] [datetime] DEFAULT GETDATE(),
PRIMARY KEY (LOOKUPRoleID)
    )
GO

Adding test data to LOOKUPRole table

INSERT INTO LOOKUPRole (RoleName,RoleDescription,RowCreatedSYSUserID,RowModifiedSYSUserID)
       VALUES ('Admin','Can Edit, Update, Delete',1,1)
INSERT INTO LOOKUPRole (RoleName,RoleDescription,RowCreatedSYSUserID,RowModifiedSYSUserID)
       VALUES ('Member','Read only',1,1)

SYSUser table

USE [DemoDB]
GO

CREATE TABLE [dbo].[SYSUser](
    [SYSUserID] [int] IDENTITY(1,1) NOT NULL,
    [LoginName] [varchar](50) NOT NULL,
    [PasswordEncryptedText] [varchar](200) NOT NULL,
    [RowCreatedSYSUserID] [int] NOT NULL,
    [RowCreatedDateTime] [datetime] DEFAULT GETDATE(),
    [RowModifiedSYSUserID] [int] NOT NULL,
    [RowModifiedDateTime] [datetime] DEFAULT GETDATE(),
    PRIMARY KEY (SYSUserID)
)

GO

SYSUserProfile table

USE [DemoDB]
GO


CREATE TABLE [dbo].[SYSUserProfile](
    [SYSUserProfileID] [int] IDENTITY(1,1) NOT NULL,
    [SYSUserID] [int] NOT NULL,
    [FirstName] [varchar](50) NOT NULL,
    [LastName] [varchar](50) NOT NULL,
    [Gender] [char](1) NOT NULL,
    [RowCreatedSYSUserID] [int] NOT NULL,
    [RowCreatedDateTime] [datetime] DEFAULT GETDATE(),
    [RowModifiedSYSUserID] [int] NOT NULL,
    [RowModifiedDateTime] [datetime] DEFAULT GETDATE(),
    PRIMARY KEY (SYSUserProfileID)
    )
GO

ALTER TABLE [dbo].[SYSUserProfile]  WITH CHECK ADD FOREIGN KEY([SYSUserID])
REFERENCES [dbo].[SYSUser] ([SYSUserID])
GO

and finally, the SYSUserRole table

USE [DemoDB]
GO

CREATE TABLE [dbo].[SYSUserRole](
    [SYSUserRoleID] [int] IDENTITY(1,1) NOT NULL,
    [SYSUserID] [int] NOT NULL,
    [LOOKUPRoleID] [int] NOT NULL,
    [IsActive] [bit] DEFAULT (1),
    [RowCreatedSYSUserID] [int] NOT NULL,
    [RowCreatedDateTime] [datetime] DEFAULT GETDATE(),
    [RowModifiedSYSUserID] [int] NOT NULL,
    [RowModifiedDateTime] [datetime] DEFAULT GETDATE(),
    PRIMARY KEY (SYSUserRoleID)
)
GO

ALTER TABLE [dbo].[SYSUserRole]  WITH CHECK ADD FOREIGN KEY([LOOKUPRoleID])
REFERENCES [dbo].[LOOKUPRole] ([LOOKUPRoleID])
GO

ALTER TABLE [dbo].[SYSUserRole]  WITH CHECK ADD FOREIGN KEY([SYSUserID])
REFERENCES [dbo].[SYSUser] ([SYSUserID])
GO

That’s it. We have just created four (4) database tables. The next step is to create the web application.

Adding a New ASP.NET MVC 5 Project

Go ahead and fire up Visual Studio 2015 and select File > New > Project. Under “New Project” dialog, select Templates > Visual C# > ASP.NET Web Application. See the figure below for your reference.

Image 4

Figure 4: ASP.NET Web Application template

Name your project to whatever you like and then click OK. Note that for this demo I have named the project as “MVC5RealWorld”. Now after that you should be able to see the “New ASP.NET Project” dialog as shown in the figure below:

Image 5

Figure 5: New ASP.NET Project dialog

The New ASP.NET Project dialog for ASP.NET 4.6 templates allows you to select what type of project you want to create, configure any combination of ASP.NET technologies such as WebForms, MVC or Web API, configure unit test project, configure authentication option and also offers a new option to host your website in Azure cloud. Adding to that it also provide templates for ASP.NET 5 (recently named as ASP.NET Core).

In this series, I will only be covering on creating an ASP.NET MVC 5 application. So the details of each configuration like unit testing, authentication, hosting in cloud, etc. will not be covered.

Now select “Empty” under ASP.NET 4.6 templates and then check the “MVC” option under folders and core reference as shown in Figure 5. The reason for this is that we will create an empty MVC application from scratch.  Click OK to let Visual Studio generate the necessary files and templates needed for you to run an MVC application.

You should now be seeing something like below:

Image 6

Figure 6: The MVC5RealWorld project

Setting Up the Data Access

For this example, I’m going to use a Database-First approach with Entity Framework 6 (EF) as our data access mechanism so that we can just program against the conceptual application model instead of programming directly against our database.

Umm Huh? What do you mean?

This could simply mean that using EF you will be working with entities (class/object representation of your data structure) and letting the framework handle the basic select, update, insert & delete. In traditional ADO.NET you will write the SQL queries directly against tables/columns/procedures and you don't have entities so it’s much less objecting oriented.

I prefer using EF because it provides the following benefits:

  • Applications can work in terms of a more application-centric conceptual model, including types with inheritance, complex members, and relationships.
  • Applications are freed from hard-coded dependencies on a particular data engine or storage schema.
  • Mappings between the conceptual model and the storage-specific schema can change without changing the application code.
  • Developers can work with a consistent application object model that can be mapped to various storage schemas, possibly implemented in different database management systems.
  • Multiple conceptual models can be mapped to a single storage schema.
  • Language-integrated query (LINQ) support provides compile-time syntax validation for queries against a conceptual model.

You can read more about it here: ADO.NET Entity Framework At-a-Glance

Creating the Entity Models

Now let’s setup our Model folder structure by adding the following sub-folders under the “Models” folder:

  • DB
  • EntityManager
  • ViewModel

Our model structure should look something like below:

Image 7

Figure 7: Creating the Models folder

The DB folder is where we store our entity data model (.EDMX). You can think of it as a conceptual database that contains some tables. To add an entity, right click on the DB folder and select Add > New Item > Data > ADO.NET Entity Data Mode as shown in the figure below.

Image 8

Figure 8: Adding Entity Data Model

You can name your entity model as you would like, but for this example I just named it as “DemoModel” for simplicity. Now click “Add” to continue and on the next step select “EF Designer from Database” as we are going to use database first approach to work with existing database. Click “Next” to proceed. In the next step click on “New Connection” button and then select “Microsoft SQL Server (SqlClient)” as the data source, then click “Next”.

You should see this dialog below:

Image 9

Figure 9: Connection Properties dialog

Enter the SQL server name and select the database that we have just created in previous steps. If you have an existing database, then use that instead. Also note that I am using windows authentication for logging in to my SQL Server. Once you’ve done supplying the necessary fields, you can then click on “Test Connection” to verify the connectivity. If it is successful then just click “OK”.

You should now see the following dialog below:

Image 10

Figure 10: Choose Your Data Connection dialog

Notice that the connection string was automatically generated for you. Click “Next” and then select “Entity Framework 6.x” to bring up the following dialog below:

Image 11

Figure 11: Entity Data Model Wizard dialog

Now select the table(s) that you want to use in your application. For this example I selected all tables because we are going to use those in our application. Clicking the “Finish” button will generate the entity models for you as shown in the figure below:

Image 12

Figure 12: The Entity Data Model

What happens there is that EF automatically generates the business objects for you and let you query against it. The EDMX or the entity data model will serve as the main gateway by which you retrieve objects from database and resubmit changes.

Creating a Signup Page

Adding ViewModels

As a recap, Entity Framework will generate the business model objects and manage Data Access within the application. As a result, the class LOOKUPRole, SYSUserRole, SYSUser and SYSUserProfile are automatically created by EF and it features all the fields from the database table as properties of each class.

I don't want to use these classes directly in the View so I’ve decided to create a separate class that just holds the properties I needed in the View. So let's add the “UserModel” class by right-clicking on the "ViewModel" folder and then selecting Add > Class.  The "UserModel.cs" file is where we put all user related model views. For the Signup page we are going to add the “UserSignUpView” class. In the “UserModel.cs” file add the following code below:

using System.ComponentModel.DataAnnotations;

namespace MVC5RealWorld.Models.ViewModel
{
   
    public class UserSignUpView
    {
        [Key]
        public int SYSUserID { get; set; }
        public int LOOKUPRoleID { get; set; }
        public string RoleName { get; set; }
        [Required(ErrorMessage = "*")]
        [Display(Name = "Login ID")]
        public string LoginName { get; set; }
        [Required(ErrorMessage = "*")]
        [Display(Name = "Password")]
        public string Password { get; set; }
        [Required(ErrorMessage = "*")]
        [Display(Name = "First Name")]
        public string FirstName { get; set; }
        [Required(ErrorMessage = "*")]
        [Display(Name = "Last Name")]
        public string LastName { get; set; }
        public string Gender { get; set; }
    }
}

Notice that I have added the “Required” and “DisplayName” attributes for each property in the UserSignUpView class. This attributes is called Data Annotations. Data annotations are attribute classes that lives under System.ComponentModel.DataAnnotations namespace that you can use to decorate classes or properties to enforce pre-defined validation rules.

I'll use this validation technique because I want to keep a clear separation of concerns by using the MVC pattern and couple that with data annotations in the model, then your validation code becomes much simpler to write, maintain, and test.

For more information about Data Annotations then you can refer this article from MSDN: Data Annotations . And of course you can find more examples about it by doing a simple search at google :)

Adding the UserManager Class

The next step that we are going to do is to create the “UserManger” class that would handle the CRUD operations (Create, Read, Update and Delete operations) of a certain table. The purpose of this class is to separate the actual data operations from our controller and to have a central class for handling insert, update, fetch and delete operations.

Notes:

Please keep in mind that in this article I'm only be doing the insert part in which a user can add new data from the View to the database. I'll talk about how to do update, fetch and delete with MVC in my next article. So this time we'll just focus on the insertion part first.

Since this demo is intended to make web application as simple as possible then I will not be using TransactionScope and Repository pattern. In real complex web app, you may want to consider using TransactionScope and Repository for your Data Access.

Now right click on the "EntityManager" folder and then add a new class by selecting Add > Class and name the class as "UserManager". Here's the code block for the "UserManager" class:

using System;
using System.Linq;
using MVC5RealWorld.Models.DB;
using MVC5RealWorld.Models.ViewModel;

namespace MVC5RealWorld.Models.EntityManager
{
    public class UserManager
    {
        public void AddUserAccount(UserSignUpView user) {

            using (DemoDBEntities db = new DemoDBEntities()) {

                SYSUser SU = new SYSUser();
                SU.LoginName = user.LoginName;
                SU.PasswordEncryptedText = user.Password;
                SU.RowCreatedSYSUserID = user.SYSUserID > 0 ? user.SYSUserID : 1;
                SU.RowModifiedSYSUserID = user.SYSUserID > 0 ? user.SYSUserID : 1; ;
                SU.RowCreatedDateTime = DateTime.Now;
                SU.RowMOdifiedDateTime = DateTime.Now;

                db.SYSUsers.Add(SU);
                db.SaveChanges();

                SYSUserProfile SUP = new SYSUserProfile();
                SUP.SYSUserID = SU.SYSUserID;
                SUP.FirstName = user.FirstName;
                SUP.LastName = user.LastName;
                SUP.Gender = user.Gender;
                SUP.RowCreatedSYSUserID = user.SYSUserID > 0 ? user.SYSUserID : 1;
                SUP.RowModifiedSYSUserID = user.SYSUserID > 0 ? user.SYSUserID : 1;
                SUP.RowCreatedDateTime = DateTime.Now;
                SUP.RowModifiedDateTime = DateTime.Now;

                db.SYSUserProfiles.Add(SUP);
                db.SaveChanges();


                if (user.LOOKUPRoleID > 0) {
                    SYSUserRole SUR = new SYSUserRole();
                    SUR.LOOKUPRoleID = user.LOOKUPRoleID;
                    SUR.SYSUserID = user.SYSUserID;
                    SUR.IsActive = true;
                    SUR.RowCreatedSYSUserID = user.SYSUserID > 0 ? user.SYSUserID : 1;
                    SUR.RowModifiedSYSUserID = user.SYSUserID > 0 ? user.SYSUserID : 1;
                    SUR.RowCreatedDateTime = DateTime.Now;
                    SUR.RowModifiedDateTime = DateTime.Now;

                    db.SYSUserRoles.Add(SUR);
                    db.SaveChanges();
                }
            }
        }

        public bool IsLoginNameExist(string loginName) {
            using (DemoDBEntities db = new DemoDBEntities()) {
                return db.SYSUsers.Where(o => o.LoginName.Equals(loginName)).Any();
            }
        }
    }
}

The AddUserAccount() is a method that inserts data to the database using Entity Framework. The IsLoginNameExist() is a method that returns boolean. It basically checks the database for an existing data using LINQ syntax. I'm trying this demo as simple as possible but the code above can be refactored, for example you can create a method that accepts a dynamic type. You can then pass the common properties to that method and add them to the dynamic object. 

Adding the Controllers

Since our model was already set then let's go ahead and add the "AccountController" class. To do this, just right click on the "Controllers" folder and select Add > Controller > MVC 5 Controller -Empty and then click “Add”.  In the next dialog name the controller as "AccountController" and then click “Add” to generate class for you.

Here’s the code block for the "AccountController" class:

using System.Web.Mvc;
using System.Web.Security;
using MVC5RealWorld.Models.ViewModel;
using MVC5RealWorld.Models.EntityManager;

namespace MVC5RealWorld.Controllers
{
    public class AccountController : Controller
    {      
        public ActionResult SignUp() {
            return View();
        }

        [HttpPost]
        public ActionResult SignUp(UserSignUpView USV) {
            if (ModelState.IsValid) {
                UserManager UM = new UserManager();
                if (!UM.IsLoginNameExist(USV.LoginName)) {
                    UM.AddUserAccount(USV);
                    FormsAuthentication.SetAuthCookie(USV.FirstName, false);
                    return RedirectToAction("Welcome", "Home");

                }
                else
                    ModelState.AddModelError("", "Login Name already taken.");
            }
            return View();
        }
    }
}

The “AccountController class has two main methods. The first one is the "SignUp" which returns the "SignUp.cshtml" View when that action is requested. The second one also named as "SignUp" but it is decorated with the "[HttpPost]" attribute. This attribute specifies that the overload of the "SignUp" method can be invoked only for POST requests.

The second method is responsible for inserting new entry to the database and automatically authenticate the users using FormsAuthentication.SetAuthCookie() method. This method creates an authentication ticket for the supplied user name and adds it to the cookies collection of the response or to the URL if you are using cookieless authentication. After authenticating, we then redirect the users to the “Welcome.cshtml” page.

Now add another Controller and name it as "HomeController". This controller would be our controller for our default page. We will create the "Index" and the "Welcome" View for this controller in the next step. Here's the code for the "HomeController" class:

using System.Web.Mvc;

namespace MVC5RealWorld.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index() {
            return View();
        }

        [Authorize]
        public ActionResult Welcome() {
            return View();
        }

    }
}

The HomeController class consists of two ActionResult methods such as Index and Welcome. The "Index" method serves as our default redirect page and the "Welcome" method will be the page where we redirect users after they have authenticated successfully. We also decorated it with the "[Authorize]" attribute so that this method will only be available for the logged-in or authenticated users.

To configure a default page route, you can go to App_Start > RouteConfig. From there you should be able to see something like this:

public static void RegisterRoutes(RouteCollection routes)
{
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
}

The code above signifies that the URL path /Home/Index is the default page for our application. For more information about Routing, visit:  ASP.NET MVC Routing Overview

Adding the Views

There are two possible ways to add Views. Either you can manually create the Views folder by yourself and add the corresponding .CSHTML files or by right clicking on the Controller’s action method just like in the figure shown below:

Image 13

Figure 13: Adding new View

Clicking “Add” View will show this dialog below:

Image 14

Figure 14: Add View dialog

Just click “Add” since we don’t need to do anything with the Index page at this point. Now modify the Index page and replace it with the following HTML markup:

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Index</h2>
<br/>
No Account yet? @Html.ActionLink("Signup Now!", "SignUp", "Account")

The ActionLink in the markup above allows you to navigate to the SignUp page which lives under AccountController. Now add a View to the Welcome action by doing the same as what we did by adding the Index page. Here’s the Welcome page HTML markup:

@{
    ViewBag.Title = "Welcome";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Hi <b>@Context.User.Identity.Name</b>! Welcome to my first MVC 5 Web App!</h2>

Now switch back to “AccountControllerclass and add a new View for the “SignUp” page. In the Add View dialog select “Create” as the scaffold template, select the “UserSignUpView” as the model and the “DemoDBEntities” as the data context as shown in the figure below:

Image 15

Figure 15: Add View dialog

Click “Add” to let Visual Studio scaffolds the UI for you. The term “Scaffolding” allow you to quickly generate the UI that you can edit and customize.

Now we need to trim down the generated fields because there are some fields that we don’t actually need users to see like the RoleName and ID’s.  Adding to that I also modified the Password to use the PasswordFor HTML helper and use DropDownListFor for displaying the Gender. Here’s the modified and trimmed down HTML markup for the SignUp page:

@model MVC5RealWorld.Models.ViewModel.UserSignUpView

@{
    ViewBag.Title = "SignUp";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>SignUp</h2>

@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()
    
    <div class="form-horizontal">
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <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.PasswordFor(model => model.Password, 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="Register" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to Main", "Index","Home")
</div>

The markup above is a strongly-type view. This strongly typed approach enables better compile-time checking of your code and richer IntelliSense in the Visual Studio editor. By including a @model statement at the top of the view template file, you can specify the type of object that the view expects. In this case it uses the MVC5RealWorld.Models.ViewModel.UserSignUpView.

If you also noticed, after adding the views, Visual Studio automatically structures the folders for your Views. See the figure below for your reference:

Image 16

Figure 16: The newly added Views

Web.Config

The final piece is to add the following configuration under system.web node to enable forms authentication:

 <system.web>
    <authentication mode="Forms">
      <forms loginUrl="~/Account/Login" defaultUrl="~/Home/Welcome"></forms>
    </authentication>    
</system.web>

Running the Application

Now compile and build you application. Here are the following outputs when you run the page in the browser:

On initial request

Image 17

Figure 17: Initial request

Page validation triggers

Image 18

Figure 18: Page Validation

Supplying the required fields

Image 19

Figure 19: Supplying the Required fields

And after successful registration

Image 20

That’s it! I hope you will find this article useful.

Check out the next article for creating a Login form with page authorizaton here.

Summary

In Part 1 of the series, we've learned the following:

  • Brief overview of ASP.NET MVC
  • Creating a database in MS SQL Server
  • Creating a database tables in MS SQL Server
  • Creating an ASP.NET MVC 5 project in Visual Studio
  • Implementing Entity Framework Database-First approach
  • Creating Models, Views and Controllers
  • Creating a simple Signup page

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here