Web Application Development - Lab
Web Application Development - Lab
NET MVC
FRAMEWORK
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.
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.
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>
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.
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.
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.
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.
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.
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.
2.2.2. App_Start:
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.
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
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.
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:
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.
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.
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();
}
}
}
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.
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.
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.
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.
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.
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.
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.
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.
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.
@{
ViewBag.Title = “Index”;
You continue to add new controllers. Each controller adds a number of Actions and
generates an interface for the corresponding Action.
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; }
}
}
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.
Once you created the required models for your application, then the model folder
structure should look like below.
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();
}
}
}
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.
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.
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.
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();
}
}
}
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">
That’s it. Now run the application and you will see the employee details on the
webpage as expected.
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.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.
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;
return View();
}
}
}
As you can see in the above example, here we are using ViewBag to pass the data.
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>
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.
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
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; }
}
}
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.
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.
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()
{
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.
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>
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.
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.
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
}
);
}
}
}
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.
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}.
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.
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();
}
}
}
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; }
}
}
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)
{
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)
@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>
namespace AttributeRoutingDemoInMVC.Controllers
{
[RoutePrefix("students")]
public class StudentsController : Controller
{
static List<Student> students = new List<Student>()
{
new Student() { Id = 1, Name = "Pranaya" },
[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
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
This can be very easily achieved using Attribute Route Constraints in the ASP.NET
MVC application. To specify attribute route constraint, the syntax is
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
Example:
[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
[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