MVC
MVC
MVC
Net MVC
Why MVC?
Develop a giant application like ERP
MVC is one of the most frequently used industry-standard web development framework to
create scalable and extensible projects.
If we see in asp.net Webforms as we have various server control which generates large view
state to maintain state which make page heavy. If person having low bandwidth cannot
access this Heavy page. At this time we can use MVC where we have control over Generating
HTML and using some Functionality of MVC such as bundling and minification can increase
performance of application.
Using this pattern, user requests are routed to a Controller which is responsible for working
with the Model to perform user actions and/or retrieve results of queries.
The Controller chooses the View to display to the user, and provides it with any Model data
it requires.
Model Responsibilities
The Model in an MVC application represents the state of the application and any business
logic or operations that should be performed by it.
Business logic should be encapsulated in the model, along with any implementation logic for
persisting the state of the application.
Model Responsibilities
Kalpesh Padhariya
ASP.Net MVC
Strongly-typed views typically use ViewModel types designed to contain the data to display
on that view.
The controller creates and populates these ViewModel instances from the model.
View Responsibilities
Views are responsible for presenting content through the user interface.
They use the Razor view engine to embed .NET code in HTML markup.
There should be minimal logic within views, and any logic in them should relate to
presenting content.
If you find the need to perform a great deal of logic in view files in order to display data from
a complex model, consider using a View Component, ViewModel, or view template to
simplify the view.
Controller Responsibilities
Controllers are the components that handle user interaction, work with the model, and
ultimately select a view to render.
In an MVC application, the view only displays information; the controller handles and
responds to user input and interaction.
In the MVC pattern, the controller is the initial entry point, and is responsible for selecting
which model types to work with and which view to render (hence its name - it controls how
the app responds to a given request).
Add Controller
Add in Menu
Welcome Method
View.Bag
ViewData
Kalpesh Padhariya
ASP.Net MVC
Add Create
[HttpPost]
public ActionResult Create([Bind(Include =
"Person_Name,Mobile_No,Email_ID,Address")] Person Person)
Add ConfirmDelete
[HttpPost, ActionName(“Delete”)]
Attributes
Key
Required
Display
EmailAddress
StringLength
RegularExpression
Password
[DataType(DataType.Password)]
Compare
Execute No Query
getData
Kalpesh Padhariya
ASP.Net MVC
Transaction
Empty
Internet Application
Intranet Application
Empty
Web Forms
MVC
Web API
Folders
/App_Data
XML files
/bin
The compiled assembly for your MVC application is placed here, along with any
referenced assemblies that are not in the GAC (Global Assembly Cache).
/Content
Kalpesh Padhariya
ASP.Net MVC
This is where you put static content such as CSS files and images.
/Scripts
This directory is intended to hold the JavaScript libraries for your application. Visual
Studio adds the libraries for jQuery and Microsoft AJAX helpers by default.
/Controls
/Models
This is where you put your view model and domain model classes, although all but
the simplest applications benefit from defining the domain model in a dedicated
project, as we demonstrated for Sports Store.
/Views
This directory holds views and partial views, usually grouped together in folders
named after the controller with which they are associated.
The /Views/Web.config file prevents IIS from serving the content of these
directories. Views must be rendered through an action method.
/Views/Shared
This directory holds layouts and views which are not specific to a single controller.
For security reasons, IIS won’t serve files whose full paths contain Web.config, bin,
App_code, App_GlobalResources, App_LocalResources, App_WebReferences, App_Data, or
App_Browsers.
IIS will also filter out requests for .asax, .ascx, .sitemap, .resx, .mdb, .mdf, .ldf, .csproj, and
various other file name extensions.
If you do decide to restructure your project, you must be sure not to use these names and
extensions in your URLs.
/Areas
These contain resource files used for localizing Web Forms pages.
/App_Browsers
Kalpesh Padhariya
ASP.Net MVC
This folder contains .browser XML files that describe how to identify specific web
browsers, and what such browsers are capable of (whether they support JavaScript,
for example).
/App_Themes
This folder contains Web Forms themes (including .skin files), which influence how
Web Forms controls are rendered.
Files
/Views/Web.config
This is not the configuration file for your application. It contains the configuration
required to make views work with ASP.NET and prevents views from being served by
IIS.
/Global.asax
This is the global ASP.NET application class. Its code-behind class (Global.asax.cs) is
the place to register routing configuration, as well as set up any code to run on
application initialization or shutdown, or when unhandled exceptions occur.
The Global.asax file has the same role in an MVC application as it does in a Web
Forms application.
/Web.config
The Web.config file has the same role in an MVC application as it does in a Web
Forms application.
Convention
ASP.NET MVC applications, by default, rely heavily on conventions. This allows developers to
avoid having to confi gure and specify things that can be inferred based on convention.
For instance, MVC uses a convention-based directory-naming structure when resolving View
templates, and this convention allows you to omit the location path when referencing views
from within a Controller class.
By default, ASP.NET MVC looks for the View template fi le within the \Views\
[ControllerName]\ directory underneath the application.
ASP.NET MVC’s conventions are pretty straightforward. This is what is expected of your
application’s structure:
Kalpesh Padhariya
ASP.Net MVC
Each controller’s class name ends with Controller: ProductController,
HomeController, and so on, and lives in the Controllers directory.
There is a single Views directory for all the views of your application
Views that controllers use live in a subdirectory of the Views main directory and are
named according to the controller name (minus the Controller suffi x). For example,
the views for the ProductController discussed earlier would live in /Views/Product
The view which bind with any model is called as strongly typed view.
HTML Helpers
ASP.NET MVC Framework itself contains extension methods for HtmlHelper class to have
well structured helper methods separation.
Asp .Net MVC allow more flexible to extend the HelmHelper class to create our own custom
helper method.
HTML Helper methods will return string as output. if we want to write your own Html Helper
method we have to create extension methods for HtmlHelper class.
There are many extension methods for HtmlHelper class, which creates different html
controls.
Html.ActionLink
Html.DisplayNameFor
Html.DisplayFor
Kalpesh Padhariya
ASP.Net MVC
Returns HTML markup for the expression, using a display template.
Html.ValidationMessageFor()
It displays a validation message if an error exists for the specified field in the
ModelStateDictionary object.
Html.ValidationSummary()
Html.HiddenFor()
Html.LabelFor()
Html.EditorFor()
Kalpesh Padhariya
ASP.Net MVC
Password: @Html.EditorFor(m => m.Password)
Html.BeginForm()
The BeginForm HTML helper asks the routing engine how to reach the Search action
of the HomeController.
BeginForm helper outputs both the opening <form> and the closing </form>.
<form action="/Students/Edit/b2e006c2-5580-45fa-880c-c9cdf33b68ed"
method="post">
<form action="/Students/Delete/63ba170a-e8bf-4472-b8d7-60f602b32bf1"
method="post">
Html.DropDownListFor()
Html.TextArea()
Html.Label()
Html.TextBox()
Html.ListBox()
Postback Data
ASP.NET Web Forms supports only one server-side form in a web page, usually expressed as
<form runat=“server”>, which is a container for the View State data and post back logic.
Kalpesh Padhariya
ASP.Net MVC
MVC doesn’t use server-side forms.
Instead of Post back concept, MVC has a concept of View() method. In which we can pass
model data and bind with controls.
Based on the C# programming language, that enables the programmer to use an HTML
construction workflow.[clarification needed] Instead of using the ASP.NET Web Forms
(.aspx) markup syntax with <%= %> symbols to indicate code blocks
Razor syntax starts code blocks with an @ character and does not require explicit closing of
the code-block.
The idea behind Razor is to provide an optimized syntax for HTML generation using a code-
focused templating approach, with minimal transition between HTML and code.
The design reduces the number of characters and keystrokes, and enables a more fluid
coding workflow by not requiring explicitly denoted server blocks within the HTML code.
Razor is an ASP.NET programming syntax used to create dynamic web pages with the C# or
VB.NET programming languages.
Razor was in development in June 2010 and was released for Microsoft Visual Studio 2010 in
January 2011.
Razor is a simple-syntax view engine and was released as part of MVC 3 and the WebMatrix
tool set.
@
{
var items = new string[] {"one", "two", "three"};
}
<html>
<head>
<title>Sample View</title>
</head>
<body>
<h1>Listing @items.Length items.</h1>
<ul>
@foreach(var item in items)
{
<li>The item name is @item.</li> }
</ul>
</body>
</html>
Code Expressions
Kalpesh Padhariya
ASP.Net MVC
Variable Declaration and use.
@{
string rootNamespace = "MyApp";
}
<span>@rootNamespace.Models</span>
<span>@(rootNamespace).Models</span>
<span>MyApp.Models</span>
We should also look at the case where you intend to show an e-mail address. For example,
consider the following e-mail address.
<span>[email protected]</span>
At first glance, this seems like it would cause an error because @megacorp.com looks like a
valid code expression where we’re trying to print out the com property of the divineerp
variable. Fortunately, Razor is smart enough to recognize the general pattern of an e-mail
address and will leave this expression alone.
<li>[email protected]</li>
In this particular case, that expression seems to match an e-mail address, so Razor will print
it out verbatim. But it just so happens that you expected the output to be something like:
<li>Item_3</li>
HTML Encoding
This code does not result in an alert box popping up but instead renders the encoded HTML:
<span><script>alert('haacked!');</script></span>
You can also create an instance of HtmlString or use the Html.Raw convenience method.
<span><strong>This is bold!</strong></span>
Kalpesh Padhariya
ASP.Net MVC
<script type="text/javascript">
window.onload = function ()
{
var message = 'Hello @ViewBag.Username';
alert(message);
}
</script>
AJAX
<tr [email protected]_ID>
<script type="text/javascript">
function deleteSuccess(rowid) {
$('#' + rowid).remove();
alert(‘Record is deleted.');
};
</script>
Microsoft.jQuery.Unobtrusive.Ajax
Entity Framework (EF) is an open source object-relational mapping (ORM) framework for
ADO.NET.
The Entity Framework is a set of technologies in ADO.NET that support the development of
data-oriented software applications.
Architects and developers of data-oriented applications have typically struggled with the
need to achieve two very different objectives.
Kalpesh Padhariya
ASP.Net MVC
Add connection string to web.config
<add name="MyConnection" connectionString="server=.\DE_17_Debug; Initial
Catalog=MVC_Demo; uid=sa; pwd=sqladmin;" providerName="System.Data.SqlClient"/>
Create a Controller.
Index Action
return View(db.DbPersons.ToList());
Details Action
Edit Action
db.Entry(Person).State = System.Data.Entity.EntityState.Modified;
Delete Action
DeleteConfirm Action
Kalpesh Padhariya
ASP.Net MVC
if (!string.IsNullOrEmpty(searchString))
lstStudent = lstStudent.Where(s => s.Person_Name.Contains(searchString));
The repository pattern is intended to create an abstraction layer between the data access
layer and the business logic layer of an application.
It is a data access pattern that prompts a more loosely coupled approach to data access.
We create the data access logic in a separate class, or set of classes, called a repository with
the responsibility of persisting the application's business model.
For the entity type we'll create a repository interface and a repository class.
When we instantiate the repository in our controller, we'll use the interface so that the
controller will accept a reference to any object that implements the repository interface.
When the controller runs under a web server, it receives a repository that works with the
Entity Framework.
MVC controllers interact with repositories to load and persist an application business model.
The diagram shows the relationship between the repository and Entity Framework data
context, in which MVC controllers interact with the repository rather than directly with
Entity Framework.
Kalpesh Padhariya
ASP.Net MVC
Kalpesh Padhariya
ASP.Net MVC
The Inversion of Control (IoC) pattern is abstract; it says that one should move dependency
creation out of the consumer class, but it doesn’t talk about exactly how to achieve that.
Two popular ways to apply the inversion of control pattern to achieve this responsibility
shift: Service Locator and Dependency Injection.
Dependency Injection
Dependency Injection (DI) is a software design pattern that allows us to develop loosely
coupled code.
DI is a great way to reduce tight coupling between software components. DI also enables us
to better manage future changes and other complexity in our software.
If you take a closer look at Dependency Injection (DI), it is a software design pattern which
enables the development of loosely coupled code.
Through DI, you can decrease tight coupling between software components. It is also known
as Inversion-of-Control, which makes unit testing convenient.
Constructor Injection
This technique involves creating a constructor for your class that expresses all of its
dependencies explicitly
e.g.
public PersonsController (IPersonsRepository Repository)
{
Kalpesh Padhariya
ASP.Net MVC
_PersonsRepository = Repository;
}
Property Injection
As the name implies, dependencies for a class are injected by setting public properties on
the object rather than through the use of constructor parameters.
e.g.
public IPersonsRepository _PersonsRepository { get; set; }
Method Injection
Inject the dependency into a single method and generally for the use of that method.
e.g.
public void InsertPerson(Persons Person)
{
db.DbPersons.Add(Person);
Save();
}
View Techniques
Using Styles
Simply create a static class with static method which will return the HTML string to be used
at the time of rendering.
Simple extension method for the built in html helper class. this will enable us to use the
same Html object to use our custom helper method.
Kalpesh Padhariya
ASP.Net MVC
size:24px\">{Content}</label>";
return new HtmlString(LableStr);
}
}
Layouts
Layouts in Razor help maintain a consistent look and feel across multiple views in your
application.
In some ways, it’s like an abstract base class for your views.
The ViewBag.Title property that we set in the Index view is read and used as the content of
the HTML title element.
Instead of an ASPX-style content placeholder, Razor includes the body of the view using the
@RenderBody() call.
Much like a master page, a Razor layout contains the HTML, script, and other elements that
you want to avoid duplicating in your views.
Bundling and minifi cation features are provided by classes in the System.Web.Optimization
namespace.
As the namespace implies, these classes are designed to optimize the performance of a web
page by minifying files (reducing their size) and bundling fi les (combining multiple fi les into
a single download).
The combination of bundling and minification generally decreases the amount of time
needed to load a page into the browser.
When you create a new ASP.NET MVC 5 application, you’ll find bundles are automatically
configured for you during application startup.
Kalpesh Padhariya
ASP.Net MVC
The configured bundles will live in a fi le named BundleConfig.cs in the App_Start folder of a
new project. Inside is code like the following to configure script bundles (JavaScript) and
style bundles (CSS)
bundles.Add(new ScriptBundle("~/bundles/jquery")
.Include( "~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval")
.Include( "~/Scripts/jquery.validate*"));
bundles.Add(new StyleBundle("~/Content/css")
.Include( "~/Content/bootstrap.css", "~/Content/site.css"));
Partial View
Partial views are contained within their own files and are reusable across views, which can
help reduce duplication, especially if you need to render the same kind of data in several
places in your application.
e.g.
@Html.Partial("DisplayPerson", Model)
Razor Helpers
The @helper syntax within Razor enables you to easily create re-usable helper methods that
can encapsulate output functionality within your view templates.
They enable better code reuse, and can also facilitate more readable code. Let’s look at a
super-simple scenario of how the @helper syntax can be used.
Example-1
@helper Display(){
<p>This is Razor Helper</p>
}
Example-2
@helper Display_Mobile_No(string Mobile_No){
if (string.IsNullOrEmpty(Mobile_No)) {
<p>No Mobile</p>
}
else {
<p>@Mobile_No</p>
}
}
Kalpesh Padhariya
ASP.Net MVC
We can define the @helper method outside of our view template, and enable it to be re-
used across all of the view templates in our project.
We can accomplish this by saving our @helper methods within .cshtml/.vbhtml files that are
placed within a \App_Code directory that you create at the root of a project.
Razor Helpers
Implement
@Razor_Helper.Display_Mobile_No(item.Mobile_No)
HtmlHelper class includes two extension methods to generate a hidden field (<input
type="hidden">) element in a razor view: Hidden() and HiddenFor().
The Html.Hidden() method generates a input hidden field element with specified name,
value and html attributes.
Example: 1
Razor View:
@Html.Hidden("StudentId", "1")
HTML:
<input
id="StudentId"
name="StudentId"
type="hidden"
value="1" />
HiddenFor helper method is a strongly typed extension method. It generates a hidden input
element for the model property specified using a lambda expression.
Example: 2
Kalpesh Padhariya
ASP.Net MVC
Razor View:
@Html.HiddenFor(m => m.StudentId)
HTML:
<input data-val="true"
id="StudentId"
name="StudentId"
type="hidden"
value="3b87bd73-fa24-4926-893f-03aed0e3a6f5" />
Session Management
Session Time Out: After session time out, all the session variables will be deleted.
Session.Timeout = 30; // time out in minutes
Application State
What is Routing?
Routing is a pattern matching system. Routing maps an incoming request (from the browser)
to particular resources (controller & action method).
This means routing provides the functionality to define a URL pattern that will handle the
request.
Kalpesh Padhariya
ASP.Net MVC
URL Pattern
domain.com/Persons/Edit/1
1 is id
General process of request: Client sends the request to the server and processes it and
produces the output.
Routing parses the request in route configuration. Then, it matches the request in the route
table to ensure which controller and which action will be processed.
Kalpesh Padhariya
ASP.Net MVC
Route
Basically, Route is an approach which defines URL pattern and handles the information. In
MVC, routes decide which Controller method to be executed on a particular request.
Configure a Route
Each MVC application has a default route which is defined in RouteConfig class under the
App_Start folder.
Kalpesh Padhariya
ASP.Net MVC
Route Table
If a URL match is found then request goes to the related controller action method.
Type of Routing
Conventional or Traditional Routing also is a pattern matching system for URL that maps
incoming request to the particular controller and action method.
We set all the routes in the RouteConfig file. RouteConfig file is available in the App_Start
folder.
Kalpesh Padhariya
ASP.Net MVC
Attribute Routing
Attribute routing gives you more control over the URIs in your web application.
Route URLs
A route’s job is to map a request to an action. The easiest way to do this is using an attribute
directly on an action method:
[Route("")]
[Route("home")]
[Route("home/index")]
public ActionResult Index()
{
return View();
}
Route Values
The static routes you saw earlier are great for the simplest routes, but not every URL is
static.
For Example, if action shows the details for a person record, we might want to include the
record ID in the URL. That’s solved by adding a route parameter:
Route URLs
[Route("Persons/{id}")]
public ActionResult Details(int id)
{
// Do some work
return View();
}
Kalpesh Padhariya
ASP.Net MVC
[Route("{year:int}/{month:int}/{day:int}")]
public string BirthDate(int year, int month, int day)
{
return $"Your birthdate is {day}/{month}/
{year}";
}
Kalpesh Padhariya