MVC 2
MVC 2
NET MVC
ASP.NET is a free web framework for building websites and web applications on .NET
Framework using HTML, CSS, and JavaScript. ASP.NET MVC 5 is a web framework based
on Model-View-Controller (MVC) architecture. Developers can build dynamic web
applications using ASP.NET MVC framework that enables a clean separation of concerns,
fast development, and TDD ( Test Driven Development) friendly.
Using the MVC pattern for websites, requests are routed to a Controller that is responsible
for working with the Model to perform actions and/or retrieve data. The Controller chooses
the View to display and provides it with the Model. The View renders the final page, based
on the data in the Model.
1. Model
2. View
3. Controller
Model
Model: Model is a part of the application which implements the logic for the data domain of
the application. It is used to retrieve and store model state in a database such as SQL Server
database. It also used for business logic separation from the data in the application.
View
View: View is a component that forms the application's user interface. It is uses to create
web pages for the application. An example would be an edit view of a Products table that
displays text boxes, drop-down lists and check boxes based on the current state of a Product
object. View in ASP.NET MVC is HTML, CSS, and some special syntax (Razor syntax) that
makes it easy to communicate with the model and the controller.
Controller
Controller: Controller is the component which handles user interaction. It works with the
model and selects the view to render the web page. In an MVC application, the view only
displays information whereas the controller handles and responds to the user input and
requests.
The controller handles the user request. Typically, the user uses the view and raises an HTTP
request, which will be handled by the controller. The controller processes the request and
returns the appropriate view as a response.
This design pattern is a lightweight framework which is integrated with various features
such as master pages and membership based authentication. It is defined in
the System.Web.Mvc assembly.
The following figure illustrates the interaction between Model, View, and Controller.
MVC Architecture
The following figure illustrates the flow of the user's request in ASP.NET MVC.
As per the above figure, when a user enters a URL in the browser, it goes to the
webserver and routed to a controller. A controller executes related view and models for
that request and create the response and sends it back to the browser.
// GET: /people
public async Task Index()
{
return View(await
_context.People.ToListAsync());
}
// GET: /people/details/5
public async Task Details(int
id)
{
var person = await
_context.People.Find(id);
if (person == null)
{
return NotFound();
}
return View(person);
}
}
Views with Razor
The Razor syntax provides a simple,
clean, and lightweight way to render
HTML content based on your view.
Razor lets you render a page using C#,
producing fully HTML5 compliant web
pages.
ASP.NET MVC - Life Cycle
The life cycle is basically is set of certain stages which occur at a certain time.
MVC has two life cycles −
The application life cycle refers to the time at which the application process actually begins
running IIS until the time it stops. This is marked by the application start and end events in
the startup file of your application.
Points to Remember
Click on file menu from the menu bar and select new submenu to create a new
project. The following image show that how to create a new project.
Here, select type of project as a web project and provide name of the project.
3. Select MVC template
After selecting project type, now select the web template that we want to
implement. Since we are working on MVC then select MVC template from the list of
available template. At the same time, provide the authentication type to the
application.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplicationDemo.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
}
Index file is default for the home controller in the view folder.
Example: Index.cshtml
@{
ViewBag.Title = "Home Page";
}
< div class="jumbotron">
<h1>ASP.NET</h1>
<p class="lead">ASP.NET is a free web framework for building great Web sites and
Web applications
using HTML, CSS and JavaScript.</p>
<p><a href = "https://asp.net" class="btn btn-primary btn-lg">Learn more</a></p>
</div>
<div class="row">
<div class="col-md-4">
<h2>Getting started</h2>
<p>
ASP.NET MVC gives you a powerful, patterns-based way to build dynamic
websites that
enables a clean separation of concerns and gives you full control over
markup
for enjoyable, agile development.
</p>
<p><a class="btn btn-default" href="https://go.microsoft.com/fwlink/?
LinkId=301865">
Learn more</a></p>
</div>
<div class="col-md-4">
<h2>Get more libraries</h2>
<p>NuGet is a free Visual Studio extension that makes it easy to add, remove,
and update libraries
and tools in Visual Studio projects.</p>
<p><a class="btn btn-default" href="https://go.microsoft.com/fwlink/?
LinkId=301866">
Learn more</a></p>
</div>
<div class="col-md-4">
<h2>Web Hosting</h2>
<p>You can easily find a web hosting company that offers the right mix of
features and price
for your applications.</p>
<p><a class="btn btn-default" href="https://go.microsoft.com/fwlink/?
LinkId=301867">
Learn more</a></p>
</div>
</div>
Output:
This project produces the following output, when view in the browser.
ASP.NET Controller Actions and Parameters
In ASP.NET MVC application, the controller defines action methods that are used to handle
user requests and render view as the response. A controller can have any number of
actions.
A user request can be any of like: entering URL into the browser, clicking a link or submitting
a form.
The MVC application uses the routing rules that are defined in the Global.asax.cs file. This
file is used to parse the URL and determine the path of the controller. Now, controller
executes the appropriate action to handle the user request.
We can also create action method that returns any type of object like: integer, string etc.
To add action to the existing controller, we need to define a public method to our controller.
Our MusicStoreController.cs file is looks like the following after adding a welcome action
method.
Example: MusicStoreController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplicationDemo.Controllers
{
public class MusicStoreController : Controller
{
// GET: MusicStore
public ActionResult Index()
{
return View();
}
To access the welcome action method, execute the application then access it by
using MusicStore/Welcome URL. It will produce the following output.
The parameters are retrieved from the request's data collection. It includes name/value
pairs for form data, query string value etc. the controller class locates for the parameters
values based on the RouteData instance. If the value is present, it is passed to the
parameter. Otherwise, exception is thrown.
The Controller class provides two properties Request and Response that can be used to get
handle user request and response.
Example
Here, we are creating an action method in the controller. This action method has a
parameter. The controller code looks like this:
Example: MusicStoreController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplicationDemo.Controllers
{
public class MusicStoreController : Controller
{
// GET: MusicStore
public ActionResult Index()
{
return View();
}
Output:
In URL, we have to pass the parameter value. So, we are doing it by this URL localhost:port-
no/MusicStore/ShowMusic?MusicTitle=Classic. it produces the following result.
1. ActionName
2. ActionVerbs
ActionName
This attribute allows us to specify a different name for the action method. It is useful when
we want to call action by different name.
Example
Here, we are using ActionName attribute to apply different name for the index action
method. The controller code looks like this:
Example: MusicStoreController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplicationDemo.Controllers
{
public class MusicStoreController : Controller
{
[ActionName("store")]
public ActionResult Index()
{
return View();
}
}
}
Example: store.cshtml
@{
ViewBag.Title = "store";
}
The following output is produced when action is called with different name "store".
ActionVerbs
ASP.NET MVC provides action verbs that are applied on the action methods and works for
HttpRequest methods. There are various ActionVerbs and listed below.
HttpPost
HttpGet
HttpPut
HttpDelete
HttpOptions
ActionVerbs are name of the http requests that a controller handle. We can use it for
selection among the action methods.
Example
Example: MusicStoreController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplicationDemo.Controllers
{
public class MusicStoreController : Controller
{
[HttpGet]
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Welcome()
{
return View();
}
}
}
Example: index.cshtml
<div class="jumbotron">
<h2>Welcome to the music store.</h2>
</div>
ASP.NET MVC Model Binding
Model binding is a process in which we bind a model to controller and view. It is a simple
way to map posted form values to a .NET Framework type and pass the type to an action
method as a parameter. It acts as a converter because it can convert HTTP requests into
objects that are passed to an action method.
Example
Here, we are creating an example, in which a simple model is binding with the view and
controller. We are creating a Student model that has some properties. These properties will
be used to create form fields.
Create a Model
Right click on the Model folder and add a class to create new model.
3.7M
1.2K
This file contains some default code, but we have added some properties to it. Model looks
like this:
Example: Student.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MvcApplicationDemo.Models
{
public class Student
{
public int ID { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string Contact { get; set; }
}
}
Create a Controller
After creating model, now let's create a controller for this class. Right click on
the Controller folder and add the controller class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplicationDemo.Controllers
{
public class StudentsController : Controller
{
// GET: Students
public ActionResult Index()
{
return View();
}
}
}
Creating a View
To create view right click within the body of Index action method and select Add
View option, it will pop up for the name of the view and Model to attach with the view.
After adding, it generates an index file within the Students folder that contains the following
code.
Example: Index.cshtml
@model MvcApplicationDemo.Models.Student
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Student</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class =
"control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Name, new { htmlAttributes = new
{ @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Name, "", new { @class =
"text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Email, htmlAttributes: new { @class =
"control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Email, new { htmlAttributes = new
{ @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Email, "", new { @class =
"text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Contact, htmlAttributes: new { @class =
"control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Contact, new { htmlAttributes = new {
@class = "form-control" } })
@Html.ValidationMessageFor(model => model.Contact, "", new { @class
= "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
Output:
MVC has certain conventions for project structure. The view file should be located in the
subdirectory of View folder.
MVC uses Razor view engine so that we can write server side code in HTML as well. Let's
create a view and execute it to the browser.
Example: Welcome.cshtml
@{
ViewBag.Title = "Welcome";
}
<h2>Welcome</h2>
Example: StudentController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplicationDemo.Controllers
{
public class StudentsController : Controller
{
// GET: Students
public ActionResult Index()
{
return View();
}
public ActionResult Welcome()
{
return View();
}
}
}
This controller has Welcome action method that will render Welcome view file to the
browser. Right click on the Welcome.cshtml file and select view in browser. This will
produce the following output.
Output:
Routing in MVC
In the ASP.NET Web Forms application, every URL must match with a specific .aspx file.
For example, a URL http://domain/studentsinfo.aspx must match with the file
studentsinfo.aspx that contains code and markup for rendering a response to the
browser.
Routing is not specific to the MVC framework. It can be used with ASP.NET Webform
application or MVC application.
ASP.NET introduced Routing to eliminate the needs of mapping each URL with a physical
file. Routing enables us to define a URL pattern that maps to the request handler. This
request handler can be a file or class. In ASP.NET Webform application, request handler is
.aspx file, and in MVC, it is the Controller class and Action method. For example,
http://domain/students can be mapped to http://domain/studentsinfo.aspx in ASP.NET
Webforms, and the same URL can be mapped to Student Controller and Index action
method in MVC.
Route
Route defines the URL pattern and handler information. All the configured routes of an
application stored in RouteTable and will be used by the Routing engine to determine
appropriate handler class or file for an incoming request.
Every MVC application must configure (register) at least one route configured by the
MVC framework by default. You can register a route in RouteConfig class, which is
in RouteConfig.cs under App_Start folder. The following figure illustrates how to
configure a route in the RouteConfig class .
As you can see in the above figure, the route is configured using
the MapRoute() extension method of RouteCollection, where name is "Default", url
pattern is "{controller}/{action}/{id}" and defaults parameter for controller, action
method and id parameter. Defaults specify which controller, action method, or value of id
parameter should be used if they do not exist in the incoming request URL.
In the same way, you can configure other routes using the MapRoute() method of
the RouteCollection class. This RouteCollection is actually a property of
the RouteTable class.
URL Pattern
The URL pattern is considered only after the domain name part in the URL. For example,
the URL pattern "{controller}/{action}/{id}" would look like
localhost:1234/{controller}/{action}/{id}. Anything after "localhost:1234/" would be
considered as a controller name. The same way, anything after the controller name
would be considered as action name and then the value of id parameter.
Routing in MVC
If the URL doesn't contain anything after the domain name, then the default controller
and action method will handle the request. For example, http://localhost:1234 would be
handled by the HomeController and the Index() method as configured in the default
parameter.
The following table shows which Controller, Action method, and Id parameter would
handle different URLs considering the above default route.
Multiple Routes
You can also configure a custom route using the MapRoute extension method. You need
to provide at least two parameters in MapRoute, route name, and URL pattern. The
Defaults parameter is optional.
You can register multiple custom routes with different names. Consider the following
example where we register "Student" route .
Example: Custom Routes
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Student",
url: "students/{id}",
defaults: new { controller = "Student", action = "Index"}
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id
= UrlParameter.Optional }
);
}
}
As shown in the above code, the URL pattern for the Student route is students/{id}, which
specifies that any URL that starts with domainName/students, must be handled by
the StudentController. Notice that we haven't specified {action} in the URL pattern
because we want every URL that starts with students should always use the Index() action
of the StudentController class. We have specified the default controller and action to
handle any URL request, which starts from domainname/students.
MVC framework evaluates each route in sequence. It starts with the first configured
route, and if incoming URL doesn't satisfy the URL pattern of the route, then it will
evaluate the second route and so on. In the above example, routing engine will evaluate
the Student route first and if incoming URL doesn't start with /students then only it will
consider the second route which is the default route.
The following table shows how different URLs will be mapped to the Student route:
You can also apply restrictions on the value of the parameter by configuring route
constraints. For example, the following route applies a limitation on the id parameter
that the id's value must be numeric.
routes.MapRoute(
name: "Student",
url: "student/{id}/{name}/{standardId}",
defaults: new { controller = "Student", action = "Index", id =
UrlParameter.Optional, name = UrlParameter.Optional, standardId =
UrlParameter.Optional },
constraints: new { id = @"\d+" }
);
So if you give non-numeric value for id parameter, then that request will be handled by
another route or, if there are no matching routes, then "The resource could not be
found" error will be thrown.
Register Routes
Now, after configuring all the routes in the RouteConfig class, you need to register it in
the Application_Start() event in the Global.asax so that it includes all your routes into
the RouteTable.
Points to Remember :
1. Routing plays important role in the MVC framework. Routing maps URL to physical
file or class (controller class in MVC).
2. Route contains URL pattern and handler information. URL pattern starts after the
domain name.
3. Routes can be configured in RouteConfig class. Multiple custom routes can also be
configured.
4. Route constraints apply restrictions on the value of parameters.
5. Route must be registered in Application_Start event in Global.ascx.cs file.