0% found this document useful (0 votes)
16 views

MVC 2

ASP.NET MVC is a web framework that uses the model-view-controller (MVC) pattern to build dynamic websites. MVC separates an application into three main components: the model, the view, and the controller. The model manages the application's data and logic. The view displays the model's data. The controller handles user input and interaction by updating the model and selecting a view to render. Using MVC, ASP.NET developers can build web applications with clean separation of concerns, fast development, and test-driven development.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

MVC 2

ASP.NET MVC is a web framework that uses the model-view-controller (MVC) pattern to build dynamic websites. MVC separates an application into three main components: the model, the view, and the controller. The model manages the application's data and logic. The view displays the model's data. The controller handles user input and interaction by updating the model and selecting a view to render. Using MVC, ASP.NET developers can build web applications with clean separation of concerns, fast development, and test-driven development.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 31

ASP.

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.

The MVC (Model-View-Controller) is a design pattern used to decouple user-interface


(view), data (model), and application logic (controller). This pattern helps to achieve
separation of concerns.

MVC with ASP.NET


ASP.NET gives you a powerful, patterns-based way to build dynamic websites using the MVC
pattern that enables a clean separation of concerns.

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.

MVC is an application development pattern or design pattern which separates an


application into three main components:

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.

The following image represents the ASP.NET MVC Design Pattern:

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.

Request Flow in MVC Architecture

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.

public class Person Models & data


{
Create clean model classes and easily
public int PersonId { get; set; }
bind them to your database.
[Required] Declaratively define validation rules,
[MinLength(2)] using C# attributes, which are applied
public string Name { get; set; } on the client and server.
[Phone]
public string PhoneNumber { get; set; } ASP.NET supports many database
engines including SQLite, SQL Server,
[EmailAddress] MySQL, PostgreSQL, DB2 and more, as
public string Email { get; set; }
well as non-relational stores such as
}
MongoDB, Redis, and Azure Cosmos
DB.
Controllers public class PeopleController :
Controller
Simply route requests to controller actions,
{
implemented as normal C# methods. Data from the private readonly
request path, query string, and request body are AddressBookContext _context;
automatically bound to method parameters.
public
PeopleController(AddressBookContext
context)
{
_context = context;
}

// 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


 The request life cycle

The Application Life Cycle

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.

The Request Life Cycle


It is the sequence of events that happen every time an HTTP request is handled by our
application.
The entry point for every MVC application begins with routing. After the ASP.NET platform
has received a request, it figures out how it should be handled through the URL Routing
Module.
Modules are .NET components that can hook into the application life cycle and add
functionality. The routing module is responsible for matching the incoming URL to routes
that we define in our application.
All routes have an associated route handler with them and this is the entry point to the MVC
framework.
The MVC framework handles converting the route data into a concrete controller that can
handle requests. After the controller has been created, the next major step is Action
Execution. A component called the action invoker finds and selects an appropriate Action
method to invoke the controller.
After our action result has been prepared, the next stage triggers, which is Result Execution.
MVC separates declaring the result from executing the result. If the result is a view type, the
View Engine will be called and it's responsible for finding and rending our view.
If the result is not a view, the action result will execute on its own. This Result Execution is
what generates an actual response to the original HTTP request.

Benefits of ASP.NET MVC


Following are the benefits of using ASP.NET MVC −
 Makes it easier to manage complexity by dividing an application into the model, the
view, and the controller.
 Enables full control over the rendered HTML and provides a clean separation of
concerns.
 Direct control over HTML also means better accessibility for implementing compliance
with evolving Web standards.
 Facilitates adding more interactivity and responsiveness to existing apps.
 Provides better support for test-driven development (TDD).
 Works well for Web applications that are supported by large teams of developers and
for Web designers who need a high degree of control over the application behaviour.

 Points to Remember

1. MVC stands for Model, View and Controller.


2. Model represents the data
3. View is the User Interface.
4. Controller is the request handler.
ASP.NET MVC Project
In this topic, we are using visual studio 2017 IDE to create MVC web application. It includes
the various steps that are given below. These following steps explain how to create MVC
based web application.

1. Create a Web Project

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.

2. Select Project Type

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.

After clicking ok, it creates a project that has following structure:


4. MVC Web Application Project Structure

Following is the project structure that we just created.

See, the project carefully, it contains three folders named Model, View and Controller.


The HomeController is default controller for the application. This controller contains the
following code:
Example: HomeController.cs

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.

ActionResult Return Type


The ActionResult class is the base class for all action results. Action methods return an
instance of this class. There can be different action result types depending on the task that
the action is implementing. For example, if an action is to call the View method, the View
method returns an instance of the ViewResult which is derived from the ActionResult class.

We can also create action method that returns any type of object like: integer, string etc.

The following table contains built-in action result types.

Action Result Helper Method Description

ViewResult View It is used to render a view as a


Web page.

PartialViewResult PartialView It is used to render a partial view.

RedirectResult Redirect It is used to redirect to another


action method by using its URL.

RedirectToRouteResult RedirectToAction RedirectToRoute It is used to redirect to another


action method.

ContentResult Content It is used to return a user-defined


content type.
JsonResult Json It is used to return a serialized
JSON object.

JavaScriptResult JavaScript It is used to return a script that


can be executed on the client.

FileResult File It is used to return binary output


to write to the response.

EmptyResult (None) It represents a return value that is


used if the action method must
return a null result.

Adding an Action method


Here, we will add a new action method to the controller that we crested in previous
chapter.

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();
}

public string Welcome()


{
return "Hello, this is welcome action message";
}
}
}
Output:

To access the welcome action method, execute the application then access it by
using MusicStore/Welcome URL. It will produce the following output.

Action Method Parameters


Action parameters are the variables that are used to retrieve user requested values from
the URL.

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();
}

// Adding an Action method with Parameter


public string ShowMusic(string MusicTitle)
{
return "You selected " + MusicTitle+ " Music";
}
}
}

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.

ASP.NET MVC Action Selectors


Action selectors are attributes that are applied on action methods of a controller. It is used
to select correct action method to call as per the request. MVC provides the following action
selector attributes:

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";
}

<h2>Hello, This is Music store.</h2>


Output:

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();
}
}
}

Following is the Index file for MusicStoreController.

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.

After adding, it provides the following predefined code.


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();
}
}
}

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:

When the Index file is executed it produces the following output.

ASP.NET MVC View


The MVC View is a standard HTML page that may contain script. It is used to create web
pages for the application. Unlike ASP.NET Web Pages, MVC Views are mapped to the action
and then controller renders the view to the browser.

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.

Creating View to the Application


To add view, right click on the subfolder inside the View folder and select Add->

Add View. It will pop up for the view name etc.

This file has following default code.

Example: Welcome.cshtml

@{
ViewBag.Title = "Welcome";
}
<h2>Welcome</h2>

If we want to execute it, we have a controller like this:

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.

The following figure illustrates the Routing process.


Configure a Route

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 .

Configure Routes in MVC

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.

URL Controller Action Id

http://localhost/home HomeController Index null

http://localhost/home/index/123 HomeController Index 123

http://localhost/home/about HomeController About null

http://localhost/home/contact HomeController Contact null

http://localhost/MusicStore/Index MusicStoreController Index null

http://localhost/MusicStore/ShowMusic? MusicStoreController ShowMusic Classic


MusicTitle=Classic

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:

URL Controller Action Id

http://localhost/student/123 StudentController Index 123

http://localhost/student/index/123 StudentController Index 123

http://localhost/student?Id=123 StudentController Index 123


Route Constraints

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.

Example: Custom Routes

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.

Example: Route Registration

public class MvcApplication : System.Web.HttpApplication


{
protected void Application_Start()
{
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
}

The following figure illustrate Route registration process.


Thus, routing plays
important role in MVC
framework.

 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.

You might also like