[go: up one dir, main page]

0% found this document useful (0 votes)
82 views18 pages

Is The User Interface

ASP.NET MVC is a web framework that uses the Model-View-Controller architecture to build web applications with .NET Framework. It separates application concerns into three components: Model for data and business logic, View for user interface, and Controller for handling user requests. The document also outlines the folder structure of an MVC project, routing, controllers, action methods, model binding, and Razor syntax.

Uploaded by

Eric Mboya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
82 views18 pages

Is The User Interface

ASP.NET MVC is a web framework that uses the Model-View-Controller architecture to build web applications with .NET Framework. It separates application concerns into three components: Model for data and business logic, View for user interface, and Controller for handling user requests. The document also outlines the folder structure of an MVC project, routing, controllers, action methods, model binding, and Razor syntax.

Uploaded by

Eric Mboya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

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.

ASP.NET MVC Architecture

MVC stands for Model, View, and Controller. MVC separates an application into
three components - Model, View, and Controller.

In other words, we can say that the ASP.NET MVC is a web application
development framework from Microsoft that is based on the MVC (Model-View-
Controller) architectural design pattern.

Model: Model represents the shape of the data. A class in C# is used to describe
a model. Model objects store data retrieved from the database.

• Represents the data and business logic of the application.

• Consists of data transfer objects (DTOs), data access logic, and service
layers.

• Responsible for accessing and storing data and the associated logic.

View: View in MVC is a user interface. View display model data to the user and
also enables them to modify them. 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.

View is the User Interface.

• Handles the presentation layer of the application.

• It uses the Razor view engine to embed .NET code within HTML.

Page 1 of 18
• Responsible for displaying the application’s user interface.

Controller: 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.

Controller is the request handler.

• Acts as an intermediary between the Model and View.

• Processes incoming requests, manipulates data using the model, and


renders the final output for the view.

• Each controller action typically corresponds to a specific operation and


view.

The following figure illustrates the interaction between Model, View, and
Controller.

Page 2 of 18
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.

MVC Project

We are going to use ASP.NET MVC v5.2, and Visual Studio 2017 community edition,
and .NET Framework 4.6 to create our first MVC application.

STEPS

Open Visual Studio 2017 and select File menu -> New -> Project

From the New Project dialog, expand Visual C# node and select Web in the left
pane, and then select ASP.NET Web Application (.NET Framework) in the middle
pane.

From the New ASP.NET Web Application dialog, select MVC

Page 3 of 18
ASP.NET MVC Folder Structure

1. App_Data

The App_Data folder can contain application data files like LocalDB, .mdf files,
XML files, and other data related files. IIS will never serve files from App_Data
folder.

2. App_Start

The App_Start folder can contain class files that will be executed when the
application starts. Typically, these would be config files like AuthConfig.cs,
BundleConfig.cs, FilterConfig.cs, RouteConfig.cs etc. MVC 5 includes
BundleConfig.cs, FilterConfig.cs and RouteConfig.cs by default. We will see the
significance of these files later.

Page 4 of 18
3. Content

The Content folder contains static files like CSS files, images, and icons files. MVC
5 application includes bootstrap.css, bootstrap.min.css, and Site.css by default.

4. Controllers

The Controllers folder contains class files for the controllers. A Controller handles
users' request and returns a response. MVC requires the name of all controller files
to end with "Controller". You will learn about the controller in the next section.

5. fonts

The Fonts folder contains custom font files for your application.

6. Models

The Models folder contains model class files. Typically, model class includes public
properties, which will be used by the application to hold and manipulate
application data.

7. Scripts

The Scripts folder contains JavaScript or VBScript files for the application. MVC 5
includes javascript files for bootstrap, jquery 1.10, and modernizer by default.

8. Views

The Views folder contains HTML files for the application. Typically view file is a

. cshtml file where you write HTML and C# or VB.NET code.

The Views folder includes a separate folder for each controller. For example, all
the .cshtml files, which will be rendered by HomeController will be in View > Home
folder.

The Shared folder under the View folder contains all the views shared among
different controllers e.g., layout files.

Page 5 of 18
Additionally, MVC project also includes the following configuration files:

a. Global.asax

Global.asax file allows you to write code that runs in response to application-level
events, such as Application_BeginRequest, application_start, application_error,
session_start, session_end, etc.

b. Packages.config

Packages.config file is managed by NuGet to track what packages and versions


you have installed in the application.

c. Web.config

Web.config file contains application-level configurations.

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.

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.

Route

Route defines the URL pattern and handler information.

Page 6 of 18
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.

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’s
name would be considered as action name and then the value of id parameter.

The picture below, shows how to config route in your MVC application.

Page 7 of 18
Controllers in ASP.NET MVC

The Controller in MVC architecture handles any incoming URL request.


The Controller is a class, derived from the base class System.Web.Mvc.Controller.
Controller class contains public methods called Action methods.

Controller and its action method handles incoming browser requests, retrieves
necessary model data and returns appropriate responses.

❖ In ASP.NET MVC, every controller class name must end with a word
"Controller". For example, the home page controller name must
be HomeController, and for the student page, it must be
the StudentController. Also, every controller class must be located in
the Controller folder of the MVC folder structure.

Action method

All the public methods of the Controller class are called Action methods.

Action method must be public. It cannot be private or protected

Action method cannot be overloaded

Action method cannot be a static method.

The following illustrates the Index() action method in the StudentController class.

Page 8 of 18
ActionResult

MVC framework includes various Result classes, which can be returned from an
action method. The result classes represent different types of responses, such as
HTML, file, string, JSON, javascript, etc. The following table lists all the result classes
available in ASP.NET MVC.

Result Class Description

ViewResult Represents HTML and markup.

EmptyResult Represents No response.

ContentResult Represents string literal.

FileContentResult/ FilePathResult/ FileStreamResult Represents the content of a file.

JavaScriptResult Represent a JavaScript script.

JsonResult Represent JSON that can be used in AJAX.

RedirectResult Represents a redirection to a new URL.

RedirectToRouteResult Represent another action of same or other controller.

PartialViewResult Returns HTML from Partial view.

HttpUnauthorizedResult Returns HTTP 403 status.

The ActionResult class is a base class of all the above result classes, so it can be
the return type of action method that returns any result listed above. However,
you can specify the appropriate result class as a return type of action method.

The base Controller class includes the View() method along with other methods
that return a particular type of result, as shown in the below table.

Page 9 of 18
Action Method Parameters

Every action methods can have input parameters as normal methods

Action Selectors

Action selector is the attribute that can be applied to the action methods. It helps
the routing engine to select the correct action method to handle a particular
request. MVC 5 includes the following action selector attributes:

1. ActionName

2. NonAction

3. ActionVerbs

ActionName

The ActionName attribute allows us to specify a different action name than the
method name, as shown below.

Page 10 of 18
NonAction

Use the NonAction attribute when you want public method in a controller but do
not want to treat it as an action method.

ActionVerbs

Includes: HttpGet, HttpPost, HttpPut

The ActionVerbs selector is to handle different type of Http requests. The MVC
framework includes HttpGet, HttpPost, HttpPut, HttpDelete, HttpOptions, and
HttpPatch action verbs. You can apply one or more action verbs to an action

Page 11 of 18
method to handle different HTTP requests. If you don't apply any action verbs to
an action method, then it will handle HttpGet request by default.

The following table lists the usage of HTTP methods:

Model Binding

Bind Query String to an Action Method Parameters in MVC

The model binding refers to converting the HTTP request data (from the query
string or form collection) to an action method parameters. These parameters can
be of primitive type or complex type.

1. Binding to Primitive Type

The HTTP GET request embeds data into a query string. MVC framework
automatically converts a query string to the action method parameters provided
their names are matching. For example, the query string id in the following GET
request would automatically be mapped to the Edit() action
method's id parameter.

Page 12 of 18
2. Binding to Complex Type

Model binding also works on complex types. It will automatically convert the input
fields data on the view to the properties of a complex type parameter of an
action method in HttpPost request if the properties' names match with the fields
on the view.

Now, you can create an action method which includes the Student type
parameter. In the following example, Edit action method (HttpPost) includes
Student type parameter.

Page 13 of 18
3. FormCollection

You can also include the FormCollection type parameter in the action method
instead of a complex type to retrieve all the values from view form fields, as shown
below.

4. Bind Attribute

ASP.NET MVC framework also enables you to specify which properties of a model
class you want to bind. The [Bind] attribute will let you specify the exact properties
of a model should include or exclude in binding.

Page 14 of 18
You can also exclude the properties, as shown below.

Model Binding Process

ASP.NET MVC framework automatically converts request values into a primitive or


complex type object.

Model binding is a two-step process. First, it collects values from the incoming HTTP
request, and second, it populates primitive type or a complex type with these
values.

Value providers are responsible for collecting values from requests, and Model
Binders are responsible for populating values.

Page 15 of 18
Default value provider collection evaluates values from the following sources:

i. Previously bound action parameters, when the action is a child action


ii. Form fields (Request.Form)
iii. The property values in the JSON Request body (Request.InputStream), but
only when the request is an AJAX request
iv. Route data (RouteData.Values)
v. Querystring parameters (Request.QueryString)
vi. Posted files (Request.Files)

Razor Syntax

Razor allows you to write a mix of HTML and server-side code using C# or Visual
Basic. Razor view with visual basic syntax has .vbhtml file extension and C# syntax
has .cshtml file extension.

HTML Helpers

The HtmlHelper class renders HTML controls in the razor view. It binds the model
object to HTML controls to display the value of model properties into those controls
and also assigns the value of the controls to the model properties while submitting
a web form. So always use the HtmlHelper class in razor view instead of writing
HTML tags manually.

Page 16 of 18
The following table lists the HtmlHelper methods and HTML control each method
renders.

The difference between calling the HtmlHelper methods and using an HTML tags
is that the HtmlHelper method is designed to make it easy to bind to view data or
model data.

Page 17 of 18
References

https://www.tutorialsteacher.com/mvc/routing-in-mvc
https://dotnettutorials.net/course/asp-dot-net-mvc-tutorials/
https://learn.microsoft.com/en-us/aspnet/mvc/overview/getting-
started/introduction/getting-started
ASP.NET Razor Syntax (tutorialsteacher.com)

Page 18 of 18

You might also like