MVC

Download as pdf or txt
Download as pdf or txt
You are on page 1of 26

ASP.

Net MVC
Why MVC?
 Develop a giant application like ERP

 Easy to manage number of Modules.

 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.

What is MVC Pattern?


 The Model-View-Controller (MVC) is an architectural pattern that separates an application
into three main logical components: the model, the view, and the controller.

 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).

Get Started with App

 Create a Web App with MVC

 Add Controller

 Add in Menu

 Welcome Method

 Method with Parameters

Data Passing between View and Controller

 Add Model Class

 Add View “Index.cshtml”

 ViewData["Title"] = "Hello World“

 Passing Data from the Controller to the View

 View.Bag

 ViewData

 Add List for Models to List

Kalpesh Padhariya
ASP.Net MVC
 Add Create

 Add Create action to add data

 [HttpPost]
public ActionResult Create([Bind(Include =
"Person_Name,Mobile_No,Email_ID,Address")] Person Person)

 Add Edit action to update data

 Add Delete action to remove data

 Add ConfirmDelete

 [HttpPost, ActionName(“Delete”)]

Attributes

 Key

 Required

 Display

 [Display(Name = "Employee Name")]

 EmailAddress

 StringLength

 [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.",


MinimumLength = 6)]

 RegularExpression

 [RegularExpression(@"^[-+]{0,1}[0-9]{10,13}$"), ErrorMessage = "Please enter


proper mobile number")]

 Password

 [DataType(DataType.Password)]

 Compare

 [Compare("Password", ErrorMessage = "The password and confirmation password


do not match.")]

Data Passing between View and Controller

 Create common static class for SQL transactions

 Static Connection String

 Execute No Query

 Create Business Classes

 getData

Kalpesh Padhariya
ASP.Net MVC
 Transaction

ASP.NET MVC project templates

 Click on “Create New Project”

 Select Path of your folder

 Select “Web Templates”

 ASP.Net Web Application (.Net Framework)

 ASP.Net Core Web Application (.Net Core)

 ASP.Net Core Web Application (.Net Framework)

 ASP.Net Templates (MVC-3)

 Empty

 Internet Application

 Intranet Application

 ASP.Net Templates (MVC-5)

 Empty

 Web Forms

 MVC

 Web API

 Single Page Application

 Azure API App

Folders

 /App_Data

 This directory is where you put private data, such as

 XML files

 Databases like SQL Server Express, SQLite, or other file-based repositories.

 IIS will not allowed any one to access.

 /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).

 IIS will not allowed any one to access.

 /Content

Kalpesh Padhariya
ASP.Net MVC
 This is where you put static content such as CSS files and images.

 IIS will allowed any one to access.

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

 This is where you put your controller classes.

 IIS will not allowed any one to access.

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

 IIS will not allowed any one to access.

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

 Areas are a way of partitioning a large application into smaller pieces.

 /App_GlobalResources & /App_LocalResources

 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

 This is the configuration file for your application.

 The Web.config file has the same role in an MVC application as it does in a Web
Forms application.

 Also we can store Connection string and user defined tags.

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:

 Each controller’s class name ends with Controller: ProductController,


HomeController, and so on, and lives in the Controllers directory.

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

Strongly Typed View

 The view which bind with any model is called as strongly typed view.

 You can bind any class as model to view.

 You can access model properties on that view.

 You can use data associated with model to render controls.

HTML Helpers

 The HTML helper is a method that returns a string.

 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.

 HtmlHelper class generates html elements.

 There are many extension methods for HtmlHelper class, which creates different html
controls.

Extension Methods of HtmlHelper

 Html.ActionLink

 It creates an hyperlink tag. e.g.

 @Html.ActionLink("Create New", "Create")


<a href="/Students/Create">Create New</a>

 @Html.ActionLink("Edit", "Edit", new { Person_ID = item.Person_ID })


<a href= "/Person/Edit?Person_ID=546c3edd-bce0-40c3-9429-
b87ff648c0d6">Edit</a>

 Html.DisplayNameFor

 Gets the display name for the model.

 @Html.DisplayNameFor(model => model.Person_Name)

 Html.DisplayFor

Kalpesh Padhariya
ASP.Net MVC
 Returns HTML markup for the expression, using a display template.

 @Html.DisplayFor(modelItem => item.Person_Name)

 Html.ValidationMessageFor()

 It displays a validation message if an error exists for the specified field in the
ModelStateDictionary object.

 @Html.ValidationMessageFor(m => m.Person_Name, "", new { @class = "text-


danger" })

 Html.ValidationSummary()

 The ValidationSummary helper displays an unordered list of all validation errors in


the ModelState dictionary.

 AddModelError method for custom error message.

 ModelState.AddModelError(“Person_Name", "Name should not be blank.");

 Html.HiddenFor()

 The Html.Hidden helper renders a hidden input

 @Html.HiddenFor(model => model.Person_ID)

 <input data-val="true" data-val-required="The Person_ID field is required."


id="Person_ID" name="Person_ID" type="hidden" value="f8ab1faa-3b46-4b8b-
bd6f-174245307a0c" />

 Html.LabelFor()

 The Html.LabelFor() method generates a <label> element for a specified property of


model object.

 @Html.LabelFor(model => model.Person_Name, htmlAttributes: new { @class =


"control-label col-md-2" })

 <label class="control-label col-md-2" for="Person_Name">Person_Name</label>

 Html.EditorFor()

 EditorFor() method is a strongly typed method. It requires the lambda expression to


specify a property of the model object.

 @Html.EditorFor(model => model.Person_Name, new { htmlAttributes = new {


@class = "form-control" } })

 <input class="form-control text-box single-line" id="Person_Name"


name="Person_Name" type="text" value="Dharmesh" />

 StudentId: @Html.EditorFor(m => m.StudentId)

 Student Name: @Html.EditorFor(m => m.StudentName)

 Age: @Html.EditorFor(m => m.Age)

Kalpesh Padhariya
ASP.Net MVC
 Password: @Html.EditorFor(m => m.Password)

 isNewlyEnrolled: @Html.EditorFor(m => m.isNewlyEnrolled)

 Gender: @Html.EditorFor(m => m.Gender)

 DoB: @Html.EditorFor(m => m.DoB)

 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>.

 @using (Html.BeginForm(“Create", “Students", FormMethod.Post))

 <form action="/Students/Create" method="post">

 @using (Html.BeginForm(“Edit", “Students", FormMethod.Post))

 <form action="/Students/Edit/b2e006c2-5580-45fa-880c-c9cdf33b68ed"
method="post">

 @using (Html.BeginForm(“Delete", “Students", FormMethod.Post))

 <form action="/Students/Delete/63ba170a-e8bf-4472-b8d7-60f602b32bf1"
method="post">

 Html.DropDownListFor()

 @Html.DropDownListFor(model => model.Department_ID


, new SelectList( ViewBag.lstDepartments, "Department_ID", "Department")
, new { htmlAttributes = new { @class = "form-control" } })

 Html.TextArea()

 Html.Label()

 Html.TextBox()

 Html.ListBox()

Postback Data

 Since IsPostback is not available in ASP.NET MVC

 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.

Razor View Engine

 The Razor syntax is a template markup syntax.

 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.

 a simple Razor view that contains a bit of view logic:

 @
{
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.

 What if you had the following list items:

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

 As mentioned earlier, you can escape the @ sign with an @@ sign.

 <p> You should follow @aspnet </p>

 <p> You should follow @@aspnet </p>

HTML Encoding

 Razor expressions are automatically HTML encoded.

 @{ string message = "<script>alert('haacked!');</script>"; }


<span>@message</span>

 This code does not result in an alert box popping up but instead renders the encoded HTML:

 <span>&lt;script&gt;alert(&#39;haacked!&#39;);&lt;/script&gt;</span>

 You can also create an instance of HtmlString or use the Html.Raw convenience method.

 @{ string message = "<strong>This is bold!</strong>"; }


<span>@Html.Raw(message)</span>

 This results in the message being displayed without HTML encoding:

 <span><strong>This is bold!</strong></span>

 C# code also can be used in Java Script.

Kalpesh Padhariya
ASP.Net MVC
 <script type="text/javascript">
window.onload = function ()
{
var message = 'Hello @ViewBag.Username';
alert(message);
}
</script>

AJAX

 Delete Record through Ajax.

 @Ajax.ActionLink(" ", "DeleteAjax",


new { id = item.Student_ID },
new AjaxOptions {
HttpMethod = "GET“
, Confirm = "Are you Sure You Want to Delete " + @item.Student_Name}
, new { @class = "btn btn-danger glyphicon glyphicon-trash" })

 Assign rowed to tr-tag

 <tr [email protected]_ID>

 Add Java Script

 <script type="text/javascript">
function deleteSuccess(rowid) {
$('#' + rowid).remove();
alert(‘Record is deleted.');
};
</script>

 Required Following NuGet Package

 Microsoft.jQuery.Unobtrusive.Ajax

What is Entity Framework?

 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.

Entity Framework – Step by Step

 Create a new project

 Add NuGet package: EntityFramework

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 DAL folder

 Add DbContext Class

 Pass connection string name to base constructor

 Create a model class

 Declare a DbSet property in Context class.

 Create a Controller.

 Declare a db Context reference variable.

 Index Action

 return View(db.DbPersons.ToList());

 Details Action

 Persons Person = db.DbPersons.Find(id);

 Edit Action

 db.Entry(Person).State = System.Data.Entity.EntityState.Modified;

 Delete Action

 Persons Person = db.DbPersons.Find(id);


return View(Person);

 DeleteConfirm Action

 Persons Person = db.DbPersons.Find(id);


if (Person == null)
return HttpNotFound();
db.DbPersons.Remove(Person);
db.SaveChanges();

 Search Option in Index

 @using (Html.BeginForm("Index", "Persons", FormMethod.Get))


{
<p> Find by Name:
@Html.TextBox("SearchString")
<input type="submit" value="Search" />
</p>
}

 var lstStudent = from s in db.DbPersons


select s;

Kalpesh Padhariya
ASP.Net MVC
if (!string.IsNullOrEmpty(searchString))
lstStudent = lstStudent.Where(s => s.Person_Name.Contains(searchString));

What is Repository Pattern?

 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.

 "One-per business model" approach to design a repository in which there is a repository


class for each entity type.

 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.

 By taking advantage of dependency injection (DI), repositories can be injected into a


controller's constructor.

 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

Repository Pattern Step-by-Step

 Create new project with MVC

 Add NuGet package for Entity Framework.

 Set connection string in web.config

 Create a Model Class

 Create a folder - DAL

 Create a DataContext Class

 Declare constructor and DbSet

 Create a Repository Interface

 Create a Repository class

 Compile the project.

 Create a controller with MVC-5 with views and Entity Framework.

 Move code from controller to repository class.

Software Design Pattern

 Inversion of Control (IoC) Pattern

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.

 The purpose of DI is to make code maintainable.

 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

 Defining and using custom HTML Helpers

 Defining a layout / MVC Master Page

 Using Styles

 Defining and using partial views

 Razor Helper Method syntax

Custom HTML Helpers

 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.

 public static class Custom_Helper_Class


{
public static IHtmlString Create_Lable (string Content)
{
string LableStr = $ "<label style=\"background-color:gray;color:yellow;font-

Kalpesh Padhariya
ASP.Net MVC
size:24px\">{Content}</label>";
return new HtmlString(LableStr);
}
}

 public static class Custom_Helper_Class


{
public static IHtmlString Retrieve_Label (this HtmlHelper helper, string content)
{
string LableStr = $ "<label style=\"background-color:blue;color:red;font-
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.

 A layout is the equivalent of the ASPX master page.

 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 Minification

 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 View is a fragment of content that is embedded in another 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>
}
}

Reusing @helpers across multiple views

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

 Example-3 (Razor_Helper in App_Code)


@helper Display_Mobile_No(string Mobile_No){
if (string.IsNullOrEmpty(Mobile_No)) {
<p>No Mobile</p>
}
else {
<p>@Mobile_No</p>
}
}

 Implement
@Razor_Helper.Display_Mobile_No(item.Mobile_No)

HtmlHelper - Hidden field

 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.

 HiddenFor method binds a specified model object property to <input type="hidden">. So it


automatically sets a value of the model property to hidden field and visa-versa.

 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

 Store data in session variable


Session["SessionStart"] = DateTime.Now;

 Get data from session variable


@Session["SessionStart"]

 Session Time Out: After session time out, all the session variables will be deleted.
Session.Timeout = 30; // time out in minutes

Application State

 Application state is used to store data on the application machine.

 It works as a global variable in other programming languages.

 Application variable is an object that is shared by the multiple sessions.

 We can use application variable within page, HttpHandler and Global.asax.

 Store data in Application State


Application["Rajkot_Temperature"] = 27;
System.Web.HttpContext.Current. Application["Rajkot_Temperature"] = 27;

 Get data from Application State


@System.Web.HttpContext.Current. Application["Rajkot_Temperature"]

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.

 That is how the application matches a URI to an action.

Kalpesh Padhariya
ASP.Net MVC
URL Pattern

 domain.com/Persons/Edit/1

 domain.com is a namespace or hosting name

 Persons is a Controller name

 Edit is an action method name

 1 is id

 General process of request: Client sends the request to the server and processes it and
produces the output.

How To Work Routing

 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.

 An MVC URL consists of the following properties.

 Route Name: A route is a URL pattern that is mapped to a handler.

 A handler has a controller that can process the request.

Configure a Route

 Each MVC application has a default route which is defined in RouteConfig class under the
App_Start folder.

 The image describes the configuration of a Route in the RouteConfig class.

Kalpesh Padhariya
ASP.Net MVC

Route Table

 We define a route for each action method.

 All the routes are stored in the route table.

 Each incoming request is mapped to this route table.

 If a URL match is found then request goes to the related controller action method.

 If the URL is not found, the application returns a 404 page.

Type of Routing

 There are 2 types of Routing in MVC application

 Conventional or Traditional Routing (Using Routing Config)

 Attribute Routing (Available in MVC 5)

Conventional or Traditional 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.

 We need to register all the routes to make them operational.

 Register RouteConfig in Global.asax

Kalpesh Padhariya
ASP.Net MVC
Attribute Routing

 MVC 5 supports a new type of routing, called attribute routing.

 As the name implies, attribute routing uses attributes to define routes.

 Attribute routing gives you more control over the URIs in your web application.

 To enable attribute routing, call MapMvcAttributeRoutes during configuration.

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:

 public class HomeController : Controller


{
[Route("about")]
public ActionResult About()
{
return View();
}
}

 [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