Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Web Application Development - Lab

This document provides an introduction to the ASP.NET MVC Framework, explaining its components (Model, View, Controller) and how they interact to develop web applications. It outlines the advantages of using ASP.NET MVC, such as lightweight architecture, support for test-driven development, and a clean separation of concerns. Additionally, the document includes a step-by-step guide for creating an ASP.NET MVC application using Visual Studio and describes the default file and folder structure generated by the framework.

Uploaded by

dattq22
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Web Application Development - Lab

This document provides an introduction to the ASP.NET MVC Framework, explaining its components (Model, View, Controller) and how they interact to develop web applications. It outlines the advantages of using ASP.NET MVC, such as lightweight architecture, support for test-driven development, and a clean separation of concerns. Additionally, the document includes a step-by-step guide for creating an ASP.NET MVC application using Visual Studio and describes the default file and folder structure generated by the framework.

Uploaded by

dattq22
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

LAB 1. INTRODUCTION TO ASP.

NET MVC
FRAMEWORK

1.1. Introduction to ASP.NET MVC Framework


In this article, I am going to give you a brief Introduction to ASP.NET MVC Framework. As
part of this article, we are going to practice the following pointers in detail.
1. What is ASP.NET MVC?
2. What is MVC?
3. How Does the MVC Design Pattern Work in ASP.NET MVC Application?
4. Advantages of using ASP.NET MVC to Develop Web Applications
1.1.1. What is ASP.NET MVC?
The ASP.NET MVC is a web application development framework provided by Microsoft which
is built on top of the .NET Framework. We can use this ASP.NET MVC Framework to develop web
applications that provide a clean separation of code. The ASP.NET MVC framework is the most
extensible and customizable framework provided by Microsoft.
The ASP.NET MVC Framework is based on MVC (Model-View-Controller) Design Pattern. So
the point that I need to highlight here is ASP.NET MVC is a Framework whereas MVC is a Design
Pattern.
The ASP.NET MVC Framework is not built from ground zero. You can consider it as an
alternative approach to our traditional ASP.NET Web Forms Framework. As it is built on top of the
.NET Framework, developers enjoy almost all the ASP.NET features while working with the MVC
application.
1.1.2. What is MVC?
MVC is an architectural software design pattern that is used for developing interactive
applications where their user interaction is involved and based on the user interaction some event
handling has occurred. It is not only used for web-based applications but it can also be used for Desktop
or mobile-based applications where there are user interactions involved.
MVC design pattern was introduced in the 1970s that basically divides an application into 3
major components as Model, View, and Controller. The main objective of the MVC design pattern is
the separation of concerns (codes), which means the domain model and business logic are separated
from the user interface (i.e. view). As a result, maintenance and testing of the application become
simpler and easier.

WEB APPLICATION DEVELOPMENT Page 1


1.2. How does the MVC Design Pattern work in ASP.NET
MVC Application?
Let us understand how the MVC Design Pattern works in the ASP.NET MVC application with
an example. Let’s say we want to display the student details on a web page as shown in the below
image.

So, when the client (user) issues a request something like


“http://localhost:port/student/details/2” from a web browser then the request is handled by the MVC
framework as shown below.

The controller is the component in the ASP.NET MVC application that actually
receives the incoming HTTP request and then handles that request. In order to handle the
incoming HTTP request, the controller does several things as follows.

1. The controller creates the model object that is required by a view. The model is the
component in the MVC design pattern that contains a set of classes to represent the
domain data or business data as well as logic to manage the data.
2. The controller then selects a view to render the domain data or business data. The
point that you need to remember is, while selecting a view, it is the responsibility of
the controller to pass the model data.

WEB APPLICATION DEVELOPMENT Page 2


3. In the MVC Design Pattern, the one and only responsibility of a view is to display
the model data. So, the responsibility of a view is to generate the necessary HTML
which will render the model data or business data. Once the HTML is generated by the view,
then that HTML is then sent to the client via the controller who initially made the request.
Now, I hope you understand the basic idea of the MVC Design Pattern. Let us practice each of
the components of the MVC design pattern in detail by comparing it with our example.
1.2.1. Model

The Model is the component in the MVC design pattern that manages that business
data or domain data i.e. state of the application in memory. The Model contains a set of
classes that represent the data as well as logic to manage the data. So, in our example, the
model consists of the Student class to represent the student data as well as
StudentBusinessLayer class to retrieve the student data from any persistent medium like a
database.

WEB APPLICATION DEVELOPMENT Page 3


So in short, a Model:
1. In ASP.NET MVC is basically a C# or VB.net class to represent the data as well as
to manage the data.
2. It is accessible by both controller and view.
3. It can be used to pass data from controller action methods to a view.
4. It can also be used by a view to display data on a page (HTML output).
1.2.2. View:

The view is the component in MVC Design Pattern that renders the model data as the
user interface with which the end-user can interact. So, the View creates the user interface
with data from the model. In our example, we want to display the Student information on
a web page. So here the student model carried the student data to the view. This is the
student model which should be supplied by the controller to the view. The following code
does the same thing.

@model FirstMVCApplication.Models.Student
<html>
<head>
<title>Student Details</title>
</head>
<body>
<br />
<br />
<table>
<tr>
<td>Student ID: </td>
<td>@Model.StudentID</td>
</tr>
<tr>
<td>Name: </td>
<td>@Model.Name</td>
</tr>
<tr>
<td>Gender: </td>
<td>@Model.Gender </td>
</tr>
<tr>
<td>Branch: </td>
<td>@Model.Branch</td>
</tr>
<tr>

WEB APPLICATION DEVELOPMENT Page 4


<td>Section: </td>
<td>@Model.Section </td>
</tr>
</table>
</body>
</html>

So in short, a View
1. In ASP.NET MVC is a cshtml page.
2. It contains all page-specific HTML generation and formatting code.
3. A request to a view can only be made from a controller’s action method.
4. The one and only responsibility of a view is to render the domain data or business
data.
1.2.3. Controller:

The Controller is the component that contains the control flow logic. It is the one that
will interact with both models and views to control the flow of application execution. The
controller is the component in MVC Design Pattern that will handle the incoming HTTP
Request. Based on the user’s actions, the respective controller will work with the model
and view and then sends the response back to the user who initially made the request. In
our example, when the client issued a request to the following URL

http://localhost:port /student/details/2
Then that request is going to be mapped to the Details action method of the Student
Controller. Following is the code of our Controller class with the Details action method.

So, in short, a Controller:


1. Is basically a C# or VB.NET class that is inherited from
the System.Web.Mvc.Controller.

WEB APPLICATION DEVELOPMENT Page 5


2. Is the component which will interact with both Models and views.
3. Contains action methods that are responsible for handling the incoming HTTP
Request.
4. Can access and use the model class to pass the data to the views.

1.3. Advantages of using ASP.NET MVC Framework to

Develop Web Applications


1. It is lightweight because it does not use view state or server-based forms or server
controls.
2. Each developer based on his expertise or experience can work on different parts of
the application. For example, one developer may work on the view while the second
developer can work on the controller logic and the third developer may work on the
business logic.
3. Clean HTML and easy integration with javascript and jQuery.
4. It provides better support for test-driven development (TDD). This is because we
can focus on one aspect at a time i.e. we can focus on the view without worrying
about business logic.
5. ASP.NET MVC Framework divides the application into three main aspects as
Model, View, and Controller which make it easier to manage the application
complexity.
6. Another important advantage of the ASP.NET MVC framework is its components
are designed to be extensible and pluggable and therefore they are easily replaced
or customized.
7. The MVC framework is built on top of the ASP.NET Framework and hence we can
use most of the ASP.NET features such as authentication and authorization
scenarios, membership and roles, caching, sessions, and many more.
8. ASP.NET MVC framework supports a powerful URL routing mechanism (i.e.
attribute routing) which helps to build more user-friendly and SEO-friendly URLs
for our application.
In the next article, we are going to practice the Step-By-Step Process to Create an
ASP.NET MVC Application using Visual Studio. Here, in this article, I try to give you a
brief introduction to ASP.NET MVC Framework. I hope this article will help you with your
needs. I would like to have your feedback. Please post your feedback, question, or
comments about this article.

WEB APPLICATION DEVELOPMENT Page 6


WEB APPLICATION DEVELOPMENT Page 7
LAB 2. CREATING FIRST ASP.NET MVC
APPLICATION

2.1. Creating the First ASP.NET MVC Application using


Visual Studio
In this article, We will practice how to create the first ASP.NET MVC
Application step by step from scratch using Visual Studio 2015. You can use any version
as per your choice but the step will remain the same. Please read our previous article before
proceeding to this article where we gave a brief introduction to ASP.NET
MVC Framework.

2.1.1. Creating the First ASP.NET MVC Application

First of all, open the Visual Studio and then click on the New Project link which
appeared on the Startup page. An alternative approach to creating an application is to select
the File => New =>Project option as shown in the below image.

WEB APPLICATION DEVELOPMENT Page 8


From the New Project dialog window, from the left pane select the Web option under
the Visual C# which is under the “Installed – Templates” section. From the middle pane
select ASP.NET Web Application. Name your project as FirstMVCApplication (you can
give any name to your application). Change the location where you want to create the
application by clicking on the Browse button. Finally, click on the OK button as shown in
the image below.

Once you click on the OK button, then a new dialog window will open with the
name New ASP.NET Web Application for selecting the Project Templates. From this
window select the MVC project template. Then Change the Authentication type to No
Authentication. Finally, click on the OK button as shown in the below image.

WEB APPLICATION DEVELOPMENT Page 9


To change the authentication, you just need to click on the Change
Authentication button. Then it will open the following popup. From that popup select the
appropriate authentication mode. As we don’t want to use any authentication for this demo,
so select the No Authentication radio button and click on the OK button as shown below.

WEB APPLICATION DEVELOPMENT Page 10


Once you click on the OK button, it will take some time to create the project for us
with the following default folder structure.

2.1.2. Running the ASP.NET MVC Application:

If you want to run the project with debug mode then just press F5. On the other hand,
if you want to run the application without debugging then just Press Ctrl + F5. Once you
run the application, it will open the following page in the browser.

WEB APPLICATION DEVELOPMENT Page 11


The ASP.NET MVC 5 framework includes the necessary JavaScript and CSS files
that are required for Bootstrap by default to create a responsive web page. The responsive
web page means, the looks and feels of the web page will be changed based on the screen
size of the devices on which we are running the application. For example, if you run the
application on a mobile device, then the top menu bar will be changed as shown in the
below image.

We have done creating our first ASP.NET MVC application from scratch using Visual
Studio 2015. In the next article, we are going to practice the Folder Structure of the
ASP.NET MVC Application. Here, in this article, I try to explain how to create the first
ASP.NET MVC Application step by step from scratch using Visual Studio 2015. I hope
this article will help you with your needs. I would like to have your feedback. Please post
your feedback, question, or comments about this article.

WEB APPLICATION DEVELOPMENT Page 12


2.2. ASP.NET MVC File and Folder Structure
In this article, we are going to practice the auto-generated ASP.NET MVC File and
File Structure when we create a new ASP.NET MVC application. Please read our previous
article before proceeding to this article where we practiceed How to Create ASP.NET MVC
5 Application step by step from scratch.

Nowadays, the ASP.NET MVC framework becomes more popular among developers
because of the separation of concerns (codes) and folder structure. As a developer, it is very
important for you to understand the need and use of each file and folder of an ASP.NET
MVC application. When we create an ASP.NET MVC 5 application, Visual Studio by
default creates the following files and for our application.

Let us practice the need and use of each File and Folder in detail one by one.

WEB APPLICATION DEVELOPMENT Page 13


2.2.1. App_Data:

The App_Data folder of an ASP.NET MVC application contains application-related


data files like .mdf files, LocalDB, XML files, etc. The most important point that you need
to remember is IIS is never going to serve files from this App_Data folder. In our example,
this folder is empty as we don’t have any data files. In our upcoming articles, we will
practice how to store application-related data files in App_Data Folder.

2.2.2. App_Start:

The App_Start folder of an ASP.NET MVC application contains configuration-


related class files which are needed to be executed at the time of application starts. The
classes like BundleConfig, FilterConfig, RouteConfig, IdentityConfig, etc are stored
within this folder. We will practice the use of each of these class files in detail in our
upcoming articles.

2.2.3. Content:

The Content Folder of an ASP.NET MVC application contains static files such as
image files, CSS files, icons files, etc. When we create a new ASP.NET MVC 5 application,
then by default bootstrap.css, Site.css, and bootstrap.min.css files are included by Visual
Studio as shown in the image below.

WEB APPLICATION DEVELOPMENT Page 14


2.2.4. Controllers:

The Controllers Folder of an ASP.NET MVC application contains all the controllers
of your application. The Controllers are nothing but classes that are inherited from the base
Controller class. The name of the Controller should end with the word “Controller”. It is
this class that actually handles the user’s request i.e. the incoming HTTP Requests and
returns a response. In our upcoming articles, we will practice the controllers in detail.

2.2.5. Fonts:

The Fonts folder of an ASP.NET MVC application contains the custom font files that
are required for the application.

2.2.6. Models:

The Models folder of an ASP.NET MVC application contains the class files which
are used to store the domain data (you can also say business data) as well as business logic
to manage the data. In our example, the Models folder is empty as we have not created any
models for our application. In our upcoming articles, we will practice Models in detail.

2.2.7. Scripts:

The Scripts Folder of an ASP.NET MVC application contains all the JavaScript files
that are required for your application. When we create an ASP.NET MVC 5 application, by
default the necessary javascript files for jquery and Bootstrap are included. If you want to
create any custom javascript files then they should be created within this folder or any

WEB APPLICATION DEVELOPMENT Page 15


subfolder of this folder. This is not mandatory but it is a good programming practice as in
later time you can easily find out the javascript files.

2.2.8. Views:

The Views Folder of an ASP.NET MVC application contains all the “.cshtml” files of
your application. In MVC, the .cshtml file is a file where we need to write the HTML code
along with the C# code. The Views folder also includes separate folders for each and every
controller for your application. For example, all the .cshtml files of the HomeController
will be in the View => Home folder. We also have the Shared folder under the Views folder.
The Shared Folder contains all the views which are needed to be shared by different
controllers e.g. error files, layout files, etc.

WEB APPLICATION DEVELOPMENT Page 16


Now, let us practice the configuration files which are created by the framework by
default:

2.2.9. Global.asax:

The Global.asax file in an ASP.NET MVC application allows us to write the code that
we want to run at the application level or you can say global level, such as
Application_BeginRequest, Application_Error, Application_Start, Session_Start,
Session_End, etc. In our upcoming articles, we will practice the use of these application-
level events in detail.

2.2.10. Packages.config:

The Packages.config file in an ASP.NET MVC application is managed by NuGet


Package Manager which will keep track of what packages and versions have been installed
in your application.

2.2.11. Web.config:

The Web.config file of an ASP.NET MVC application is one of the most useful and
important files which contains the application-level configurations such as connection
strings, global variables, etc.

Here in this article, we practice the ASP.NET MVC File and Folder structure. Once
you understand the need and use of each folder and file of an MVC application, then it is
easy for you to find, store and organize project-related files.

We are going to practice Controllers in ASP.NET MVC Applications. Here, in this


article, I try to explain the need and use of ASP.NET MVC File and Folder structure which
are auto-generated by Visual Studio. I hope this article will help you with your needs.

2.3. Controllers in ASP.NET MVC Application

2.3.1. Adding Controller to the Project:

To add a controller to your project follow the below steps

WEB APPLICATION DEVELOPMENT Page 17


1. Right Click on the “Controllers” folder
2. Select Add > Controller
3. Select MVC 5 Controller – Empty
4. Click on the ADD button as shown in the image below

Once you click on the Add button, then a new pop-up window will open where you
need to provide a name for your controller. Set the Controller Name as HomeController
and click on the Add button as shown in the image below.

Once you click on the Add button, then you should have HomeController.cs within
the “Controllers” folder as shown in the below image.

WEB APPLICATION DEVELOPMENT Page 18


At this point, if you run your application, then you will get the following error.

2.3.2. Fixing the Error:

In order to fix the above error, we need to add a view with the name “Index”. We will
practice views in detail in our next article. So here we will fix the above issue in another
way. The following is the function that is auto-generated by the HomeController class.

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

WEB APPLICATION DEVELOPMENT Page 19


To fix the issue, modify the return type of the Index() action method
from “ActionResult” to “string”. Then return a string such as “Hello MVC 5
Application” as shown below.

namespace FirstMVCDemo.Controllers
{
public class HomeController : Controller
{
public string Index()
{
return "Hello MVC 5 Application";
}
}
}
With the above changes, run the application and you will see the string as expected
in the browser window. Now change the URL to http://localhost:xxxx/Home/Index

In the URL “Home” is the name of the controller and “Index” is the name of the
action method within the HomeController class. So the important point that you need to
keep in mind is the incoming URL in an ASP.NET MVC application is mapped to a
controller action method as shown in the below image.

So the next obvious question that should come to your mind is where this
mapping is defined.

WEB APPLICATION DEVELOPMENT Page 20


Well, the mapping is defined within the RegisterRoutes() method of
the RouteConfig class. As we already discussed in our ASP.NET MVC Folder and File
Structure article, all the configuration-related files are stored within the App_Start folder.
So you can find this RouteConfig class within the App_Start Folder.

Now open the RouteConfig.cs class file and you will see that
the RegisterRoutes() method of the RouteConfig class has got a default route as shown in
the below image.

In the URL, we have not specified the id value. But still, it working and we got the
output as expected. This is because as you can see in the defaults, the id parameter is
declared as optional. Let’s pass the id value in the URL and see what happens.

http://localhost:xxxx/Home/Index/10

When we navigate to the above URL nothing has happened. Now, change the
implementation of the Index() action method of the HomeController class as shown below.

WEB APPLICATION DEVELOPMENT Page 21


Now when you navigate to “/Home/Index/10“, then the value 10 is assigned to the id
parameter of the Index action method and hence it will display the following message in
the browser.

The value of Id = 10
Let’s change the implementation of the Index action method as shown below to accept
the query string parameter.

using System.Web.Mvc;
namespace FirstMVCDemo.Controllers
{
public class HomeController : Controller
{
public string Index(string id, string name)
{
return "The value of Id = " + id + " and Name =
" + name;
}
}
}
Let us issue a request as shown below using the query string.

http://localhost:xxxx/Home/Index/10?name=James

In the above URL, the value 10 is assigned to the id parameter and the query string
name is assigned to the name parameter of the Index action method. So the mapping is now
done as shown in the image below.

WEB APPLICATION DEVELOPMENT Page 22


In MVC, you can also use the “Request.QueryString” to retrieve the query string
parameter as shown below.

using System.Web.Mvc;
namespace FirstMVCDemo.Controllers
{
public class HomeController : Controller
{
public string Index(string id, string name)
{
return "Id = " + id + " ,Name = " +
Request.QueryString["name"];
}
}
}
So in short,
1. A controller in ASP.NET MVC Application is a class that is inherited
from System.Web.Mvc.Controller.
2. The MVC controller is the one that is going to interact with both Models and
views.
3. The controller class contains a set of public methods which are also called
the action methods. It is these action methods which is going to handle the
incoming HTTP Requests.

WEB APPLICATION DEVELOPMENT Page 23


4. In ASP.NET MVC, every controller class name must end with the word
“Controller”. For example, the controller for the home page must be
HomeController, and the controller for a student must be StudentController.
5. Every controller class must be located in the Controllers folder.

In the next article, we are going to practice ASP.NET MVC Views with Examples.
Here, in this article, I try to explain the Controllers in the ASP.NET MVC application with
Examples. I hope this Controllers in ASP.NET MVC Application article will help you with
your needs.

2.4. ASP.NET MVC Views


2.4.1. Example to Understand ASP.NET MVC Views:

Let’s say, we created an ASP.NET MVC application with two controllers i.e.
StudentController and HomeController. The HomeController that we created is having the
following three action methods.

− AboutUs()
− ContactUs()
− Index()

Similarly, the StudentController is created with the following four action methods.

− Index() − Edit()
− Details() − Delete()

The views are going to be created and saved in the following order.

WEB APPLICATION DEVELOPMENT Page 24


As we have two controllers in our application, so there are two folders created with
the Views folder one per Controller. The Home Folder is going to contain all the view files
(i.e. cshtml files) which are specific to HomeController. Similarly, the Student Folder is
going to contain all the .cshtml files which are specific to Student Controller. This is the
reason why, the Home folder contains the Index, AboutUs, and ContactUs cshtml files.
Similarly, the Student folder contains the Index, Details, Edit, and Delete view files.

2.4.2. Understanding Views in ASP.NET MVC with Examples

To understand the views in the ASP.NET MVC application, let us first modify the
HomeController as shown below.

using System.Web.Mvc;
namespace FirstMVCDemo.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}
}
In the above HomeController, we created an Action method that is going to return a
view. In order to return a view from an action method in ASP.NET MVC Application, we
need to use the View() extension method which is provided by System.Web.Mvc.Controller
Base class. Now run the application and navigate to the “/Home/Index” URL and you will
get the following error.

WEB APPLICATION DEVELOPMENT Page 25


Let us understand why we got the above error.

As we are returning a view from the Index action method of Home Controller, by
default the MVC Framework will look for a file with the name Index.aspx or Index.ascx
within the Home and Shared folder of the application if the view engine is ASPX. If it is
not found there then it will search for a view file with the name Index.cshtml or
Index.vbhtml within the Home and Shared folder of your application.

If the requested view file is found in any of the above locations, then the View
generates the necessary HTML and sends the generated HTML back to the client who
initially made the request. On the other hand, if the requested view file is not found in any
of the above locations, then we will get the above error.

2.4.3. Adding Views in ASP.NET MVC Application

In order to add the Index view, Right-click anywhere with the Index() function and
then click on the “Add View” option which will open the following Add View dialog
window. From the Add View window, provide the name for the view as Index, select
Template as Empty, and uncheck the checkboxes for “create as a partial view” and “use a
layout page” options. Finally, click on the Add button as shown below.

WEB APPLICATION DEVELOPMENT Page 26


Once the Index view is created, then copy and paste the following into it.

@{

ViewBag.Title = “Index”;

<h1>Index View Coming From Views/Home Folder</h1>

You continue to add new controllers. Each controller adds a number of Actions and
generates an interface for the corresponding Action.

2.5. ASP.NET MVC Models with Examples


2.5.1. Example to Understand Models in ASP.NET MVC.

We need to display the employee information on a webpage as shown below.

WEB APPLICATION DEVELOPMENT Page 27


In order to store the employee data, we are going to use the Employee model class.
To do so, right-click on the “Models” folder and then select Add => Class option. Provide
the name as Employee.cs and finally click on the Add button as shown in the image below.

Now open the Employee.cs class file and then copy and paste the following code.

namespace FirstMVCDemo.Models
{
public class Employee
{
public int EmployeeId { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string Gender { get; set; }
public decimal Salary { get; set; }
}
}

2.5.2. Creating EmployeeBusinessLayer Model:

Right-click on the Models folder and then add a new class file with the name
EmployeeBusinessLayer.cs. Once you create the EmployeeBusinessLayer class file,
then copy and paste the following code into it.

WEB APPLICATION DEVELOPMENT Page 28


namespace FirstMVCDemo.Models
{
public class EmployeeBusinessLayer
{
public Employee GetEmployeeDetails(int EmployeeId)
{
//Here we hardcoded the data
//later we will practice how to retrieve
//the data from a database
Employee employee = new Employee()
{
EmployeeId = EmployeeId,
Name = "Pranaya",
Gender = "Male",
City = "Mumbai",
Salary = 1000,
Address = "Andheri"
};
return employee;
}
}
}

Once you created the required models for your application, then the model folder
structure should look like below.

2.5.3. Modifying the HomeController

Now let us modify the HomeController class as shown below to use the Employee
and EmployeeBusinessLayer model to retrieve the employee data.

using FirstMVCDemo.Models;
using System.Web.Mvc;
namespace FirstMVCDemo.Controllers
{
public class HomeController : Controller
{
public ActionResult Index(int id)
{
EmployeeBusinessLayer employeeBL = new
EmployeeBusinessLayer();
Employee employee = employeeBL.GetEmployeeDetails(id);
return View();
}
}
}

WEB APPLICATION DEVELOPMENT Page 29


2.6. ViewData in ASP.NET MVC Application

2.6.1. How to Pass and Retrieve data From ViewData in ASP.NET MVC?

The most important point that you need to remember is, as it stores the data in the
form of an object while retrieving the data from ViewData type casting is required. If you
are accessing string data from the ViewData, then it is not required to typecast the
ViewData to string type. But it is mandatory to typecast explicitly to the actual type if you
are accessing data other than the string type.

ViewData in ASP.NET MVC with String Type:

ViewData in ASP.NET MVC with Complex Type:

2.6.2. Example of ViewData in ASP.NET MVC Application

Let us see an example to understand how to use the ViewData to pass data from a
controller action method to a view. Please read our previous article as we are going to work
with the same example. Let us first recap what we did in our previous article. First, we
create the following Employee Model to hold the employee data in memory.

WEB APPLICATION DEVELOPMENT Page 30


Then we created the following EmployeeBusinessLayer model to manage the
employee data. Here we created one method which will take the employee id as an input
parameter and returns that employee information. As of now, we have hardcoded the
employee data and in our upcoming article, we will practice retrieving the employee data
from a database like SQL Server, MySQL, Oracle, etc.

Then we modify the Index action method of Home Controller as shown below to
retrieve the employee data from EmployeeBusinesslayer and store it in the Employee
model.

WEB APPLICATION DEVELOPMENT Page 31


2.6.3. Passing ViewData From a Controller Action Method to a View:

Now we will see, how to use the ViewData to pass the employee object to the Index
view. Along with we are also going to pass the page Header using ViewData. So, modify
the Index action method of the Home Controller class as shown below.

using FirstMVCDemo.Models;

using System.Web.Mvc;

namespace FirstMVCDemo.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
EmployeeBusinessLayer employeeBL = new
EmployeeBusinessLayer();
Employee employee = employeeBL.GetEmployeeDetails(102);
ViewData["Employee"] = employee;
ViewData["Header"] = "Employee Details";
return View();
}
}
}

2.6.4. Accessing ViewData in a View:

Now we will see how to access the ViewData within an ASP.NET MVC view. So,
modify the Index Action method which is there within the Home folder in your application
as shown below.

@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Page Title</title>
</head>
<body>
@{
var employee = ViewData["Employee"]
as FirstMVCDemo.Models.Employee;
}
<h2>@ViewData["Header"]</h2>
<table style="font-family:Arial">

WEB APPLICATION DEVELOPMENT Page 32


<tr>
<td>Employee ID:</td>
<td>@employee.EmployeeId </td>
</tr>
<tr>
<td>Name:</td>
<td>@employee.Name</td>
</tr>
<tr>
<td>Gender:</td>
<td>@employee.Gender</td>
</tr>
<tr>
<td>City:</td>
<td>@employee.City</td>
</tr>
<tr>
<td>Salary:</td>
<td>@employee.Salary</td>
</tr>
<tr>
<td>Address:</td>
<td>@employee.Address</td>
</tr>
</table>
</body>
</html>

That’s it. Now run the application and you will see the employee details on the
webpage as expected.

The ViewData in MVC is resolved dynamically at runtime. As a result, it does not


provide compile-time error checking as well as we will not get the intelligence support. For
example, if we miss-spell the key names then we wouldn’t get any compile-time error
rather we came to know the error at runtime.

The ViewData in ASP.NET MVC can only transfer the data from a controller action
method to a view. That means it is valid only during the current request.

2.7. ViewBag in ASP.NET MVC Application

2.7.1. How to Pass and Retrieve data From ViewBag in ASP.NET MVC?

As the ViewBag is operating on the new dynamic data type. The advantage is that we
do not require typecasting while accessing the data from a ViewBag irrespective of the data
that we are accessing.

WEB APPLICATION DEVELOPMENT Page 33


ViewBag in ASP.NET MVC with String Type:

ViewBag in ASP.NET MVC with Complex Type:

2.7.2. Example of ViewBag in MVC Application:

Let us see an example to understand how to use the new dynamic type ViewBag in
ASP.NET MVC Application to pass data from a controller action method to a view. We are
going to work with the same example that we worked on in our previous article with
ViewData. So, modify the Index action method of HomeController class as shown below.

using FirstMVCDemo.Models;
using System.Web.Mvc;
namespace FirstMVCDemo.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
EmployeeBusinessLayer employeeBL = new
EmployeeBusinessLayer();
Employee employee = employeeBL.GetEmployeeDetails(101);

ViewBag.Employee = employee;

WEB APPLICATION DEVELOPMENT Page 34


ViewBag.Header = "Employee Details";

return View();
}
}
}

As you can see in the above example, here we are using ViewBag to pass the data.

2.7.3. Accessing the ViewBag in a View in ASP.NET MVC

Now we will see how to access the ViewBag data within an ASP.NET MVC view.
So, modify the Index.cshtml view file as shown below.

@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Page Title</title>
</head>
<body>
@{
var employee = ViewBag.Employee;
}
<h2>@ViewBag.Header</h2>
<table style="font-family:Arial">
<tr>
<td>Employee ID:</td>
<td>@employee.EmployeeId </td>
</tr>
<tr>
<td>Name:</td>
<td>@employee.Name</td>
</tr>
<tr>
<td>Gender:</td>
<td>@employee.Gender</td>
</tr>
<tr>
<td>City:</td>
<td>@employee.City</td>
</tr>
<tr>
<td>Salary:</td>
<td>@employee.Salary</td>
</tr>
<tr>
<td>Address:</td>
<td>@employee.Address</td>

WEB APPLICATION DEVELOPMENT Page 35


</tr>
</table>
</body>
</html>

As you can see, here we are accessing the data from the ViewBag using the same
dynamic properties Header and Employee. Now run the application and navigate to the
“/Home/Index” URL and you will see the data as expected on the webpage.

2.8. ViewModel in ASP.NET MVC Application

2.8.1. Understanding ViewModel in ASP.NET MVC:

Let us have a look at the following diagram which shows the visual representation of
a ViewModel in the MVC application.

Let say we want to display the employee details on a webpage. And in our application,
we have two different models to represent the employee data. The Employee Model is used
to represent the basic details of an employee whereas the Employee Address model is used
to represent the employee address.

Along with the above two models to represent the employee data, we also required
some static information like page header and title in the view. In order to achieve this, here
we need to create a view model such as EmployeeDetailsViewModel. It is this view model

WEB APPLICATION DEVELOPMENT Page 36


which is going to contain both Employee and Employee Address models as well as
properties to store the title and header of the web page.

2.8.2. Creating the Required Models:

First, create a class file with the name Employee.cs within the Models folder. The
Employee model is going to represent the basic information such as name, gender,
department, etc. Once you create the Employee.cs class file, then copy and paste the below
code in it.

namespace FirstMVCDemo.Models
{
public class Employee
{
public int EmployeeId { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
public string Department { get; set; }
public decimal Salary { get; set; }
public int AddressId { get; set; }
}
}

Now, we need to create the Address model to represent the employee Address such
as City, State, Country, etc. So, create a class file with the name Address.cs within the
Models folder and then copy and paste the following code in it.

namespace FirstMVCDemo.Models
{
public class Address
{
public int AddressId { get; set; }
public string Country { get; set; }
public string State { get; set; }
public string City { get; set; }
public string Pin { get; set; }
}
}

2.8.3. Creating the ViewModel in ASP.NET MVC:

Now it’s time to create the required View Model to store the required data which is
required for a particular view. The View Model that we are going to create will represent
the Employee Model + Employee Address Model + Some additional properties like title
and page header.

WEB APPLICATION DEVELOPMENT Page 37


In the ASP.NET MVC application, you can create the View Models anywhere within
your project, but it is always a good programming practice to create all the View Models
within a special folder called ViewModels.

So first create a folder with the name ViewModels and then create a class file with
the name EmployeeDetailsViewModel.cs within the ViewModels folder. Then copy and
paste the following code into it.

using FirstMVCDemo.Models;
namespace FirstMVCDemo.ViewModels
{
public class EmployeeDetailsViewModel
{
public Employee Employee { get; set; }
public Address Address { get; set; }
public string PageTitle { get; set; }
public string PageHeader { get; set; }
}
}

Here we created the view model class with the name as EmployeeDetailsViewModel.
Here the word Employee represents the Controller name, the word Details represent the
action method name. As it is a view model so we prefixed the word ViewModel. Although
it is not mandatory to follow this naming convention, I personally feel it is good to follow
this naming convention.

2.8.4. Creating Employee Controller:

Right-click on the Controllers folder and then add a new MVC 5 Empty controller
with the name EmployeeController.cs and then copy and paste the following code in it.

using FirstMVCDemo.ViewModels;
using FirstMVCDemo.Models;
using System.Web.Mvc;
namespace FirstMVCDemo.Controllers
{
public class EmployeeController : Controller
{
public ViewResult Details()
{
//Employee Basic Details
Employee employee = new Employee()
{

WEB APPLICATION DEVELOPMENT Page 38


EmployeeId = 101,
Name = "Dillip",
Gender = "Male",
Department = "IT",
Salary = 10000,
AddressId = 1001
};
//Employee Address
Address address = new Address()
{
AddressId = 1001,
City = "Bhubaneswar",
State = "Odisha",
Country = "India",
Pin = "755019"
};
//Creating the View model
EmployeeDetailsViewModel employeeDetailsViewModel = new
EmployeeDetailsViewModel()
{
Employee = employee,
Address = address,
PageTitle = "Employee Details Page",
PageHeader = "Employee Details",
};
//Pass the employeeDetailsViewModel to the view
return View(employeeDetailsViewModel);
}
}
}

As you can see in the above code, here we are passing the employee details view
model as a parameter to the view. And one more thing you need to notice is that now we
are not using any ViewData or ViewBag within our Details action method.

2.8.5. Creating the Details View:

First, add a folder with the name Employee within the Views folder of your
application. Once you add the Employee Folder, then you need to add a view file with the
name Details.cshtml within the Employee folder and then copy and paste the following
code in it.

@model FirstMVCDemo.ViewModels.EmployeeDetailsViewModel
@{
Layout = null;
}
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>@Model.PageTitle</title>

WEB APPLICATION DEVELOPMENT Page 39


</head>
<body>
<h1>@Model.PageHeader</h1>
<div>
EmployeeID : @Model.Employee.EmployeeId
</div>
<div>
Name : @Model.Employee.Name
</div>
<div>
Gender : @Model.Employee.Gender
</div>
<div>
Department : @Model.Employee.Department
</div>
<div>
Salary : @Model.Employee.Salary
</div>
<h1>Employee Address</h1>
<div>
City : @Model.Address.City
</div>
<div>
State : @Model.Address.State
</div>
<div>
Country : @Model.Address.Country
</div>
<div>
Pin : @Model.Address.Pin
</div>
</body>
</html>

Now, the Details view has access to the EmployeeDetailsViewModel object. By using
the @model directive, we set EmployeeDetailsViewModel as the Model for our Details
view. Then we access Employee, Address, PageTitle, and PageHeader properties using
the @Model property.

Now run the application, and navigate to the “/Employee/Details” URL and you will
see the output as expected as shown in the below image.

WEB APPLICATION DEVELOPMENT Page 40


WEB APPLICATION DEVELOPMENT Page 41
LAB 3. ASP.NET MVC – ROUTING

3.1. Routing in ASP.NET MVC Application


In this lab, we are going to practice practice Routing in the ASP.NET MVC
Application with Examples. Routing is one of the most important features of the ASP.NET
MVC Framework. As part of this article, we are going to practice the following pointers
which are related to ASP.NET MVC Routing.

3.2. How Does the Routing work in ASP.NET MVC Application?

Please have a look at the following diagram which illustrates the Routing Process in
the ASP.NET MVC Application.

In simple words, we can say that Routing in ASP.NET MVC is a pattern matching
mechanism that handles the incoming HTTP request (i.e. incoming URL) and figures out
what to do with that incoming HTTP request.

WEB APPLICATION DEVELOPMENT Page 42


When the client makes a request i.e. makes an HTTP Request, then that request is
first received by the Routing Engine. Once the Routing engine receives an HTTP Request,
then it figures out the URL Pattern of the incoming request and checks if that URL pattern
is present in the Route table. If it found a matching URL pattern for the incoming request
in the Route Table, then it fetches the corresponding handler information and forwards the
request to the appropriate controller and action method. If there is no match found in the
routing table for the incoming HTTP request URL Pattern, then it simply returns a 404
HTTP status code. The routing functionality is implemented in the System.Web.Routing.

3.3. How to Configure a Route in ASP.NET MVC?

Every ASP.NET MVC application must configure (register) at least one route in the
RouteConfig class and by default, the ASP.NET MVC Framework provides one default
route. But you can configure as many routes as you want. You can register a route within
the RegisterRoutes method of RouteConfig class, which you can find with
the RouteConfig.cs class file under the App_Start folder. You will find the following code in
the RouteConfig class.

namespace FirstMVCDemo
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default", //Route Name
url: "{controller}/{action}/{id}", //Route Pattern
defaults: new
{
controller = "Home", //Controller Name
action = "Index", //Action method Name
id = UrlParameter.Optional //Defaut value for above
defined parameter
}
);
}
}
}

WEB APPLICATION DEVELOPMENT Page 43


3.3.1. Default Route in ASP.NET MVC?

The following image shows the default route of the ASP.NET MVC application which
is created by default when we create a new ASP.NET MVC 5 Application.

As you can see in the above image, the Routing is configured using
the MapRoute() extension method of the RouteCollection class, where the Route name is
“Default” and the URL pattern is “{controller}/{action}/{id}“. The Defaults value for
the controller is Home, and the default action method is Index and the id parameter
is optional. This Route information i.e. the Route Name, URL Pattern, and handler
information i.e. the controller name, action method name are stored in the Route table at
the application start-up i.e. when the application runs for the first time.

3.3.2. Understanding the URL Pattern in ASP.NET MVC Routing:

The URL pattern is considered only after the domain name in the URL. For example,
Suppose your web application is running on www.dotnettutorials.net then the URL
pattern “{controller}/{action}/{id}” for your application would be look
like www.dotnettutorials.net/{controller}/{action}/{id}.

Anything after the “www.dotnettutorials.net/” would be considered as the controller


name. In the same way, anything after the controller name would be considered as the
action name and the value of the id parameter.

3.3.3. Understanding ASP.NET MVC Routing with an Example:

To understand ASP.NET MVC Routing lets create a controller called HomeController


as shown below.

WEB APPLICATION DEVELOPMENT Page 44


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

3.3.4. Example to understand Routing:

1. http://localhost:53605/ => controller = Home, action = Index, id = none, since


default value of controller and action are Home and Index respectively.

2. http://localhost:53605/Home => controller = Home, action = Index, id = none,


since default value of action is Index

3. http://localhost:53605/Home/Index => controller = Home, action = Index,


id=none

4. http://localhost:53605/Home/Index/5 => controller = Home, action = Index, id = 5

The default route that ASP.NET MVC Framework creates for you when you create a
new ASP.NET MVC 5 application assumes that you will follow this convention approach.
But if you want to follow your own convention then you need to modify the routes or you
need to create your own routes that we will discuss in our next article.

3.4. Custom Routes in ASP.NET MVC Application

3.4.1. Creating Custom Routes in ASP.NET MVC Application:

As we already discussed, if we want to configure any routes then we need to configure


the routes within the RegisterRoute method of RouteConfig class using the MapRoute
extension method. While configuring the Routes, at least two parameters we need to
provide to the MapRoute method i.e. Route name and URL pattern. The Default parameter
is optional.

WEB APPLICATION DEVELOPMENT Page 45


The point that you need to remember is, the Route Names must be unique. You can
register multiple custom routes with different names. Consider the following example
where we register the “Employee” route.

namespace FirstMVCDemo
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Employee",
url: " Employee/{id}",
defaults: new { controller = "Employee", action = "Index"
}
);

routes.MapRoute(
name: "Default", //Route Name
url: "{controller}/{action}/{id}", //Route Pattern
defaults: new
{
controller = "Home", //Controller Name
action = "Index", //Action method Name
id = UrlParameter.Optional //Defaut value for above
defined parameter
}
);
}
}
}

So, in this way you can configure as many as routes you want with your own URL
pattern in ASP.NET MVC Application. Let’s add Employee Controller to our application

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

WEB APPLICATION DEVELOPMENT Page 46


3.4.2. Attribute Routing in ASP.NET MVC Application

Let us understand the need for attribute routing in the ASP.NET MVC Application
with an example. Create a new Empty ASP.NET MVC application with the name
AttributeRoutingDemoInMVC. Then Right-click on the “Models” folder and add a class
file with the name Student.cs and then copy and paste the following code in it.

namespace AttributeRoutingDemoInMVC.Models
{
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
}
}

3.4.3. Creating Students Controller:

Right-click on the Controllers folder and then add a new ASP.NET MVC 5 Empty
controller with the name StudentsController.cs and then copy and paste the following code
in it.

namespace AttributeRoutingDemoInMVC.Controllers
{
public class StudentsController : Controller
{
static List<Student> students = new List<Student>()
{
new Student() { Id = 1, Name = "Pranaya" },
new Student() { Id = 2, Name = "Priyanka" },
new Student() { Id = 3, Name = "Anurag" },
new Student() { Id = 4, Name = "Sambit" }
};
[HttpGet]
public ActionResult GetAllStudents()
{
return View(students);
}
[HttpGet]
public ActionResult GetStudentByID(int studentID)
{
Student studentDetails = students.FirstOrDefault(s => s.Id ==
studentID);
return View(studentDetails);
}
[HttpGet]
public ActionResult GetStudentCourses(int studentID)
{

WEB APPLICATION DEVELOPMENT Page 47


List<string> CourseList = new List<string>();
if (studentID == 1)
CourseList = new List<string>() { "ASP.NET", "C#.NET",
"SQL Server" };
else if (studentID == 2)
CourseList = new List<string>() { "ASP.NET MVC", "C#.NET",
"ADO.NET" };
else if (studentID == 3)
CourseList = new List<string>() { "ASP.NET WEB API",
"C#.NET", "Entity Framework" };
else
CourseList = new List<string>() { "Bootstrap", "jQuery",
"AngularJs" };
ViewBag.CourseList = CourseList;
return View();
}
}
}

3.5. Route Constraints in ASP.NET MVC Attribute


Routing
3.5.1. Route Constraints in ASP.NET MVC Attribute Routing

Route Constraints in ASP.NET MVC Attribute Routing are nothing but a set of rules
that can be applied to the route parameters. By using the “:” symbol we can applied Route
Constraints to the Route Parameters. Let us understand How to use the Route Constraints
with one example. First, modify the Students Controller as shown below.

namespace AttributeRoutingDemoInMVC.Controllers
{
[RoutePrefix("students")]
public class StudentsController : Controller
{
static List<Student> students = new List<Student>()
{
new Student() { Id = 1, Name = "Pranaya" },
new Student() { Id = 2, Name = "Priyanka" },
new Student() { Id = 3, Name = "Anurag" },
new Student() { Id = 4, Name = "Sambit" }
};

[HttpGet]
[Route("{studentID}")]
public ActionResult GetStudentDetails(int studentID)

WEB APPLICATION DEVELOPMENT Page 48


{
Student studentDetails = students.FirstOrDefault(s => s.Id ==
studentID);
return View(studentDetails);
}
}
}

Create view GetStudentDetails.cshtml: Now add the GetStudentDetails view and


then copy and paste the below code into it.

@model AttributeRoutingDemoInMVC.Models.Student
@{
ViewBag.Title = "GetStudentDetails";
}
<h2>GetStudentDetails</h2>
<div>
<h4>Student</h4>
<hr />
<dl class="dl-horizontal">
<dt>
@Html.DisplayNameFor(model => model.Name)
</dt>
<dd>
@Html.DisplayFor(model => model.Name)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Id)
</dt>
<dd>
@Html.DisplayFor(model => model.Id)
</dd>
</dl>
</div>

Now If you navigate to /students/1 URL, then GetStudentDetails(int studentID)


action method is executed and we get the details of the student whose id is 1 as expected.
Let’s change our requirement, in addition to retrieving the student details by “student Id”,
we also want to retrieve the student details by “student Name“. So let’s add another
GetStudentDetails() method by taking a string parameter as shown below.

namespace AttributeRoutingDemoInMVC.Controllers
{
[RoutePrefix("students")]
public class StudentsController : Controller
{
static List<Student> students = new List<Student>()
{
new Student() { Id = 1, Name = "Pranaya" },

WEB APPLICATION DEVELOPMENT Page 49


new Student() { Id = 2, Name = "Priyanka" },
new Student() { Id = 3, Name = "Anurag" },
new Student() { Id = 4, Name = "Sambit" }
};

[HttpGet]
[Route("{studentID}")]
public ActionResult GetStudentDetails(int studentID)
{
Student studentDetails = students.FirstOrDefault(s => s.Id ==
studentID);
return View(studentDetails);
}
[HttpGet]
[Route("{studentName}")]
public ActionResult GetStudentDetails(string studentName)
{
Student studentDetails = students.FirstOrDefault(s => s.Name
== studentName);
return View(studentDetails);
}
}
}

At this point build the solution, and navigate to the following URI’s

− http://localhost:58316/students/1
− http://localhost:58316/students/Pranaya

In both the case, you will get the following error.

3.5.2. Attribute Route Constraints in ASP.NET MVC

This is because the ASP.NET MVC Framework does not know or does not identify
which version of the GetStudentDetails() action method to use when the request comes.
This is where constraints play a very important role. If an integer is specified in the URL
(/students/1), then we want to execute the GetStudentDetails(int studentId) action method
which has an integer parameter. If a string is specified in the URI (/students/Pranaya), then
we want to execute the GetStudentDetails(string studentName) action method which has
the string parameter

3.5.3. Applying Attribute Route Constraints in ASP.NET MVC

This can be very easily achieved using Attribute Route Constraints in the ASP.NET
MVC application. To specify attribute route constraint, the syntax is

WEB APPLICATION DEVELOPMENT Page 50


“{parameter:constraint}“. With these constraints in place, if the parameter segment in the
URL is an integer, then GetStudentDetails(int studentId) action method with integer
parameter is invoked, and if it is a string then GetStudentDetails(string studentName)
action method with string parameter is invoked.

Let’s modify the Student Controller to use Attribute Route Constraints as shown
below to achieve the above requirements.

namespace AttributeRoutingDemoInMVC.Controllers
{
[RoutePrefix("students")]
public class StudentsController : Controller
{
static List<Student> students = new List<Student>()
{
new Student() { Id = 1, Name = "Pranaya" },
new Student() { Id = 2, Name = "Priyanka" },
new Student() { Id = 3, Name = "Anurag" },
new Student() { Id = 4, Name = "Sambit" }
};

[HttpGet]
[Route("{studentID:int}")]
public ActionResult GetStudentDetails(int studentID)
{
Student studentDetails = students.FirstOrDefault(s => s.Id ==
studentID);
return View(studentDetails);
}
[HttpGet]
[Route("{studentName:alpha}")]
public ActionResult GetStudentDetails(string studentName)
{
Student studentDetails = students.FirstOrDefault(s => s.Name
== studentName);
return View(studentDetails);
}
}
}

Now build the solution, and navigate to the following two URIs and see everything
is working as expected.

− http://localhost:58316/students/1
− http://localhost:58316/students/Pranaya

WEB APPLICATION DEVELOPMENT Page 51


Please note that “alpha” stands for uppercase or lowercase alphabet characters. Along
with int and alpha, we also have constraints like decimal, double, float, long, bool, etc. as
shown in the below image.

3.5.4. ASP.NET MVC Attribute Route Constraints

Example:

If you want GetStudentDetails(int studentId) action method to be mapped to URI


/students/{studentId}, only if studentId is a number greater than ZERO, then use the “min”
constraint as shown below.

[Route("{studentID:int:min(1)}")]
public ActionResult GetStudentDetails(int studentID)
{
Student studentDetails = students.FirstOrDefault(s => s.Id ==
studentID);
return View(studentDetails);
}

With the above change, if you specify a positive number like 1 in the URI, then it will
be mapped to GetStudentDetails(int studentID) action method as expected

/students/1

However, if you specify 0 or a negative number, you will get an error. For example,
if you specify 0 as the value for studentID in the URI,

− http://localhost:58316/students/0

You will get the below error

WEB APPLICATION DEVELOPMENT Page 52


Error in ASP.NAlong with the “min” constraint, you can also specify the “max”
constraint as shown below. For example, if you want the studentID value in the URI to be
between 1 and 3 inclusive, then you can specify both “min” and “max” constraints as shown
below.

[HttpGet]
[Route("{studentID:int:min(1):max(3)}")]
public ActionResult GetStudentDetails(int studentID)
{
Student studentDetails = students.FirstOrDefault(s => s.Id ==
studentID);
return View(studentDetails);
}
The above example can also be achieved using just the “range” attribute
as shown below

[HttpGet]
[Route("{studentID:int:range(1,3)}")]
public ActionResult GetStudentDetails(int studentID)
{
Student studentDetails = students.FirstOrDefault(s => s.Id ==
studentID);
return View(studentDetails);
}

THE END

WEB APPLICATION DEVELOPMENT Page 53

You might also like