Full Tutorial of ASP .Net MVC in easy way
Introduction
ASP.NET MVC has become a de facto for web development on .NET platform. It is embraced by industry with aplomb and most of web applications are programmed with ASP.NET MVC. Just to reiterate ASP.NET provides pattern based way of developing web applications, websites and is TDD (i.e. test driven development) friendly.
The first version was released in 2009 and this was having only web form engine. As this version is kind of absolute with far more powerful versions coming after, the versions 2 to 5 are chosen for comparison purpose.
Description
Following table provides quick comparative analysis for different features (or attributes) among the ASP.NET MVC 2 to ASP.NET MVC 5. As these data points are self-explanatory, there seems to no need to delve into more details.
Feature / Abilities / Components
|
MVC2
|
MVC 3
|
MVC 4
|
MVC 5
|
Release Year
|
2010
|
2011
|
2012
|
2013
|
.NET Framework
|
.Net 3.5, 4.0
|
.Net 4
|
4 & 4.5
|
4.5 & 4.5.1
|
IDE
|
Visual Studio 2008 & 2010
|
Visual Studio 2010
|
Visual Studio 2010SP1 & Above
|
VS 2012 & Above
|
Default View Engine
|
Web forms View Engine (.aspx)
|
Razor and Web Forms both
|
Improved Razor Engine
| |
Multiple View Engines
|
No
|
Yes
|
Yes
|
Yes
|
Chart
|
No
|
Yes
|
Yes
|
Yes
|
WebGrid
|
No
|
Yes
|
Yes
|
Yes
|
Crypto
|
No
|
Yes
|
Yes
|
Yes
|
WebImage
|
No
|
Yes
|
Yes
|
Yes
|
JSON Binding
|
No
|
Yes
|
Yes
|
Yes
|
Entity framework
|
Version 3.5
|
Version 4
|
Version 5
|
Version 6+
|
WebMail
|
No
|
Yes
|
Yes
|
Yes
|
Data Sharing between View and Controller
| ||||
TempData
|
Yes
|
Yes
|
Yes
|
Yes
|
ViewData
|
Yes
|
Yes
|
Yes
|
Yes
|
ViewBag
|
No
|
Yes
|
Yes
|
Yes
|
HTML Layout
| ||||
Master Page
|
Yes
|
Yes
|
Yes
|
Yes
|
Layout Page
|
No
|
Yes
|
Yes
|
Yes
|
JQuery Support
|
Good
|
Better
|
Excellent
|
Excellent
|
Unobtrusive javascript validation
|
No
|
Yes
|
Yes
|
Yes
|
Project Templates
| ||||
HTML 5
|
No
|
Yes
|
Yes
|
Yes
|
JQuery Mobile
|
No
|
No
|
Yes
|
Yes
|
Bootstrap
|
No
|
No
|
No
|
Yes
|
Bundling & Minification
|
No
|
Can be implemented
|
Yes- native
|
Yes- native
|
ASP.NET Identity
|
No
|
No
|
No
|
Yes
|
Support for OAuth & OpenID
|
No
|
No
|
Yes
|
Yes
|
Authentication Filters
|
No
|
No
|
No
|
Yes
|
Filter Overrides
|
No
|
No
|
No
|
Yes
|
Attribute Routing
|
No
|
No
|
No
|
Yes
|
ASP.NET Web API
|
No
|
No
|
Yes
|
Yes – version 2.0
|
Asynchronous Controllers
|
Yes
|
Yes
|
Yes
|
Yes
|
Task Support for Asynchronous Controllers
|
No
|
No
|
Yes
|
Yes
|
Scaffolding
|
No
|
No
|
Yes
|
Yes
|
Tools support e.g. Nuget
|
No
|
Yes
|
Yes
|
Yes
|
Support for the Windows Azure SDK
|
No
|
No
|
Yes
|
Yes
|
Session-less Controller
|
No
|
Yes
|
Yes
|
Yes
|
- Asp .net MVC is a framework used to develop web application by using MVC concept.
- It was introduced in the market in the year of 2009.
- Asp .net MVC framework makes your application development is easier.
- In this MVC concept, the application development is split into multiple parts.
Q. Explain the different part in MVC?
-> MVC is actually a application development approach.
->By using this MVC, we can reduce the depending in the application models.
->In MVC based application the development split to in following parts.
1. Model
2. View
3. Controller
Model
Model part is responsible for database related logic.
It is also contents any business logic if required.
In older versions model are implemented by using A.D.O .Net.
In all lattes version of MVC models are implemented by using new data access technology called entity framework.
View The view part is responsible for presentation logic.
It will take care how to presented data to end user.
You may display the data in the from :-
(i) Paragraph
(ii) List
(iii) Table
(iv) Charts
According to our requirement.
Views are implemented by using Client side Technology for example html, css, Java script, jQuery.
In MVC application view may also conations server side programming logic(c# code)
Controller
Controller part is responsible for application execution logic.
Every request for MVC application received by controller only.
Controller is responsible for how to process the request.
Scoff Guthrie is designed ASP.Net MVC framework in 2007
ASP.Net Version
ASP.Net MVC (Beta) ---->2007
ASP.Net MVC 1.0 ----> 2009
ASP.Net MVC 2.0 ----> 2010
ASP.Net MVC 3.0 ----> 2011
ASP.Net MVC 4.0 ----> 2012
ASP.Net MVC 5.0 ----> 2012
ASP.Net MVC 5.2 ----> 2014
History of ASP.Net MVC
- Actually MVC design pattern is introduced in IT industry by TraGve Reennaky in 1970.
2. Microsoft introduced this MVC into Asp.Net in the year of 2007.
3.Scoff Guthrie is designed ASP.net MVC framework.
Software requirement for ASP.Net MVC
(i) VS 2010,2012,2013,2015,2017
(iii) ASP.Net MVC 5.0(for VS 2015)
Note:-
(i) The above software requirement for visual studio 2015.
(iii) By default vs. 2012 and 2013 provides asp.Net MVC 4 template.
Features of ASP.Net mvc
(i) S.O.C
(ii) Loosely coding(less depending)
(iii) Parallel development
(iv) Clear URL(SEO easy)
(v) TDD – Test Driven development
(vi) Unit testing is easy
(vii) Faster execution (High performance)
(viii) More controlling on Html
Q. what are the advantage ASP.NET MVC?
Q. Explain features of AsP.Net MVC?
Q.How ASP .Net MVC support more benefit compare with ASP .Net.
Separation of Code
-> It is related to separation presentation logic from database logic.
->In MVC based application we are divided application development into three separate parts (Model-View-Controller).
-> Because of this separation development and testing related phases is more comfortable.
Loosely cooping(Less depending)
->In MVC applications views are less depends on the models.
->Due to this behavior we can easily modified presentation logic which is available in the views.
For Example:
If want to display Employee information in the form of table (if all ready confine in list format). We can easily modify the view with table format without modifying the models.
Parallel development
-> MVC based application support parallel development concept.
-> In this process multi programmer can involves developing views and models parallel.
-> With this behavior development process faster.
Clean URL
->This URL’s that can use in MVC application that are called clean URL.
-> This URL can be easy readable and easy understandable.
->In MVC applications the URL’s are based on the controller.
NOTE: - In Asp .Net URL are based on the files(file based Url)
Example:
http://Filename/Loging.aspx
http://Filename/Admin/Regi.aspx
MVC URL Controller (Class)
http://sitename/Home/Login
http://sitename/Home/Reg Action Method
Because of clean URL SCO (search Engine Optimization) will be more easy.
Search engine optimization is concept of identity the website easily by search engine.
Unit Testing
-> Unit testing is a concept of testing the required portion of application.
-> The portion may be newly added method a class a web page etc.
-> By using unit testing instead of and there project we can easily test the required portion of application.
->In MVC application we can easily implemented unit testing due to it less depending behavior.
Faster execution (High performance)
->MVC application will execute will execute faster compiling the regular asp.net application.
-> MVC application’s does not support server controls.
->In Asp.Net application because of server controls view state if will degrade performance of execution process.
-> There is no server control in a view state MVC application. This result application execution is faster.
More controlling on Html
-> MVC application supports only html controls to deign view pages.
-> If we have html controls. It will be easy to integrate any kind of Client side programming.
->Most of the real time application are using lattes Client side programming concept.
Ex.
JQuery
X-UI-lib
DOJO etc
-> If any of the above Client side concept and used in MVC application.
->It is easy t controlling view designing (because view are developed with html controls)
Easy to learn and implement
->ASP .Net MVC is developed based on existing concept of .NET.
->MVC make used of .Net Library .Net language and ASP .Net concept.
ASP .Net MVC
ASP .Net Lib
.NET language(C#,VB.Net)
.Net framework
-> Because of the above implementation. If will be easy to learn and implement MVC applications for all .Net students and programmers.
Easy to modified and extend
Due to less decency behavior of MVC application if will be too easy to modify are extend the any portion of MVC application.
Developing ASP.Net mvc application
-> Asp .Net MVC is a framework Web application by using MVC design pattern.
-> Asp .Net MVC was introduced by Microsoft in the year of 2009(1.0).
->According to latest version of MVC if we want to develop asp .Net MVC application we should required a project template called asp.Net MVC 5 web application(It is a template).
-> When we create select new project we have to select .Net 4.5.
MVC5 project template
-> ASP .Net MVC 4 provides the following project tempests in order to developing MVC based application
(i) Empty
(ii) MVC
(iii) Web form
(iv) Intranet Application.
(v) Mobile Application
(vi) Web API
Note: - The above all applications will generate separate folders for Models, Views, and Controllers.
Empty-
->Empty template is similar to “Asp.Net Empty web application”.
->It will generate only empty folders.We need add all files from the search based on the requirement.
Basic
->Basic temples are simpler to “Empty” template.
-> But this template will provide extra supported files.
Eg. - Master page scripts etc.
Internet template
-> This template will generate one default readymade project.
->It uses forms Authentication security option.
->Default project contains: Home,About,Login,Register etc
Intranet Application
->This template is similar “Internet application “template”.
->But it uses windows Authentication.
Mobile Application
->It will also generate a default readymade project.
->It target mobile devices instead of regular Brower (desktop).
Web API
-> API Stand for Application programming Interface.
->Web API is service based application file web service.
-> It uses only HTTP protocol.
->It is called HTTP servers.
Web service use SOAP protocol.
NOTE:-
-> Among the above tempest “Basic” template is more comfortable for
->Beginners
->Develop the application from basic level.
But according mvc5 degine and features something differentt compression than MVC4
- ASP.NET Identity
- Attribute Routing
- Filter Overrides
- One ASP.NET
- Bootstrap
- ASP.NET Identity
Allow users to log in into Websites using social channels like Facebook, Twitter, etc.. which is possible using new ASP.NET Identity.
-> When open new ASP.Net MVC for web application. We will receive the following folders which will helps.
-> We organizing our project files.
(1) APP_Start
(2) Content
(3) Controllers
(4) Models
(5) Scripts
(6) Views
APP_Start
This folder contains files the provide application startup settings for example default controller default action method etc.
Content
This folder collection of css file.
Controller
This folder contains files the define controller classes.
Example:-
HomeContollers.cs
EmpControllers.cs
Models
This folder contains files which are providing database logic. This folder also contains additional classes which are required to process database information.
Scripts
-> This folder contains Client side programming related files (*.Js).
->It any java script libraries used in our project we need to add corresponding JS files to script fold
Ex. JQuery.
Views
->This folder contains all the view pages data record in MVC application.
->Generally this folder contains .cshtml.
NOTE: - A part above folders the following special files.
->Global.asax
->Web. Config
Programming mvc Application
-> In every MVC Application development process is start s from controller.
->After opening new project first we need to add a controller.
->In MVC application we compare each page like a method in controller.
-> These methods are called “Action method”.
->After coding action method. We need add corresponding view from presentation logic.
First MVC Application
Create MVC Application to develop the web page for following requirement:-
1. Index page
2. Course page
Steps
Create new asp.net MVC 4 web application:
Open –V.S
-> File->New -> Project->Select “ASP.Net MVC web Application”.
->Name: MVC Application Click “OK” Button
-> Select “Basic “template from project templates windows.
-> Add HomeController to our Application
->Go solution explore
-> Right Click on “Controllers” folder -> Add->Controller.
Name: HomeController
Click “Add” Button.
Note: - The above step will add file “HomeController.cs-”
It Contain a class “HomeController” and default active method “Index ()”.
->Add view page for index action method.
->Right click on Index () action method in controller file.
-> Add view
-> Name: Index
-> Click “Add” button.
Prepare the view page as our requirement.
We can add any html code in this file.
Exudes (F5) the Application.
HomeController.cs
using System.Web.Mvc
namespace MVCApplication.Controllers
{
public class HomeController: Controller
{
public ActionResult Index ()
{
return view ()
}
public ActionResult Course ()
{
return view ()
}
}
}
(ii) Index.cshtml
<h1>Welcome to MVC Application Development </h1>
<hr/><p>This page is an index page. </p>
<p>This page is an index page. </p>
<p>This page is an index page. </p>
(iii)Course.cshtml
<h1>courses page</h1>
<hr/>
<h2>Available course</h2>
<Ul>
<li>Asp .Net mvc</li>
<li>JQuery </li>
<li>Asp>Net</li>
<li>WCF</li>
</ul>
http://licalhost:1234/Home/Index
http://localhost/1234/home/Course
Create mvc Application and controller
1. The file name and Open mvc and open Basic templates.
2. Right click of controller’s
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplication.Controllers
{
public class HomeController: Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Courses()
{
return View();
}
public ActionResult ContactUs()
{
return View ();
}
}
}
-> Add view pages for action methods.
->Right click on method name(Index())
-> Add view
-> Click “Add”
And then write “Index.cshtml”
<h1>Welcome to my mvc project</h1>
<hr/>
<a href=”/Home/Course”>Courses</a>
<a href=”/Home/Contactus”>ContactUs</a>
<hr/>
<p>This is main page</p>
<p>this is main page</p>
Course.cshtml
<h1>Course page</h1>
<hr/>
<h3>Available Courses</h3>
<ul>
<li>ASP.Net MVC</li>
<li>JQuery</li>
<li>Htmlk5 and css3</li>
<li>ASP.Net MVC</li>
<li>WCF</li>
</ul>
<a href=”/”>Go to Index</a>
CoutactUs.cshtml
<h1>ContactUs page </h1>
<hr/>
<p>Farther details please contact at bellow address :< /a>
<p>
<b>Address :< /b>
Sri sai Arcade, end floor<br/>
Ameerpet<br/>
Hyderabad-500038<br/>
Phone: 040-65538968<br/>
Email:mithileshdotnet@gmail.com<br/>
<p>
<hr/>
<a href=”/”>Go to Index</a>
MVC Application Routing
-> Routing is concept of mapping the required URL to MVC application files.
-> In mvc every URL is mapping with controller and corresponding action method.
-> By default the route is mapped with “Home” controller and “index” action method.
->These default setting can modified is required.
Q: .Where do we need to modify default route settings?
-> According mvc4 these default setting available in “RoutConfig.cs”
-> This file is auto generated in “APP_Start” folder.
->This file contains setting related.
-> URL Format
->Default controller.
-> Default Action method
Class Name: Route config method: Register Routes
Q. When these default settings methods will be executed? Which file at time contains these statements?
> These setting will be exulted at the time aplication_start.
Method will call Registration Routs method.
-> This application_ start () is available in Global.asax file.
Routing is a mechanism to process the incoming url that is more descriptive and give desired response. In this case, URL is not mapped to specific files or folder as was the case of earlier days web sites.
There are two types of routing (after the introduction of ASP.NET MVC 5).
Convention based routing - to define this type of routing, we call MapRoute method and set its unique name, url pattern and specify some default values.
Attribute based routing - to define this type of routing, we specify the Route attribute in the action method of the controller.
Different types of Convention based Routing in ASP.NET
MVC
Those who are already familiar with ASP.NET MVC, the routing is defined in App_Start/RouteConfig.cs page like this (It is convention based routing)
routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } );
Where the unique name is defined for this type of url pattern and if no value is specified in the requested url for controller, action and id, the default value comes as Home, Index (id being an optional, it is not mandatory to specify in the url).
The sample url for the above route looks like this
http://localhost:63087/ - here controller and action is not passed in the url so it is set to default ie. Home and Index.
or
http://localhost:63087/home/outgoingurl - here controller is passed as "home" and action is "outgoingurl".
Using Static URL segments in Routing
In routing, we can also specify a static segments and remaining as dynamically passed variable.
In the above code snippet, the first segment of the url is hard coded, so a sample url can be
http://localhost:63075/CustomController/Index - where CustomController is the static segment and Index is the action method variable value passed in the url.
We can also amend the url parameter like "Custom/{controller}/{action}/{id}". In this case, the incoming url should look like.
http://localhost:63075/Custom/Home/Index - where Custom is static segment, Home is the controller and Index is the action method.
It can also be mixed like this "C/{controller}/{action}/{id}". In this case, the url should look like below
http://localhost:63087/CHome/Index - where C comes as static segment, Home comes from the controller variable and Index is the action variable value.
Controllers of mvc
->In mvc stands for Model View Controller.
->In mvc application execution controller plays very important roles.
->The complete execution process is take care of controller. According to mvc architecture controller is the primary responsibility to process request.
->Without controller we cannot develop MVC application.
->Controller is act as a mediator between model and the view Responsible of controller.
->According asp .net mvc controller is responsible for following activities.
1) Receives the Request
2) Process the Request
3) Sending the Response
Rules that should follow to create controller class
1. According to mvc framework the following rules need to be implemented create controller class.
2. Controller class should be declaring with “Public” access specified.
3. Class name should be end with (postfix) “controller” word
Ex.
HomeController
EmpController
DeptController
etc
4. Every “Controller” class should be inherits from “Controller” class.
“Controller” is base class from controller related classes.
Class Hierarchy of controller class
Note:-
->After complication mvc application generates a .dll in “bin” folder.
-> At the time of execution mvc engine will get the classes from * .dll (mvcApplication.dll) and executes.
-> Controller class controller IController.
System.Web. Mvc
-> Most of the class that we are using in mvc application and if define
“System.Web. Mvc” namespace.
-> System.Web.Mvc” is the imported namespace of mvc application which is created in system.web.mvc.dll (library).
Action method
->Every request to mvc application will map with controller and corresponding action method.
-> Action method contains the actually logic to process the request.
-> By default all the methods in controller class are treated as action methods.
-> A controller can create number of action methods.
->At the time of execution action methods will be invoke with controller class object.
Types of action methods
Depends on the behavior of action method these will categorize as following types.
1) Action method with view Result.
2) Action method non-view Result.
3) Non Action method.
Ex. Create mvc application to demonstrate uses of action methods types
Ans:--
1) Add HomeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplication.Controllers
{
public class HomeController:Controller
{
public ActionResult Index ()
{
return View ();
}
public ActionResult Details ()
{
Response.Write (“Student Id :”);
Response.Write (“<br>Student Name: mithilesh”);
Int total=GetTotal (75, 68, 94);
Response. Write (“<br>Total marks:”+total);
return View();
}
Public in GetTotal (int m1, int m2, int m3)
{
Int n=m1+m2+m3;
Return n;
}
Public string GetTime ()
{
String str=”Current server time:”+ Datetime.Now.Tostring (“T”);
Return str;
}
}
}
Add view page above action method:
Index.cshtml
<h1>This is index page </h1>
<hr/>
<h2>Department Details</h2>
<ol>
<li>Account </li>
<Li>IT </li>
<li>Sales </li>
<li>Hr </li>
<li>Admin </li>
</ol>
Details.cshtml
<h2>Student Details page</h2>
Then Execution (F5)
http://localhost:2132/home/Index
http://localhost:2132/home/Details
http://localhost:2132/home/GetTime
Error (Because NON Action method)
http://localhost:2132/home/GetTotal
Structure of Action method
public ActionResult Index()
{
return View();
}
->View of is a method define controller class.
-> The view () method returns object of viewResult Class.
-> ViewResult is a chilled class of action result Class.
-> Action Result is a base class for all result class in mvc
For Example
i) ViewResult
ii) JSON (java script object notation)
iii) RedirectResult.
Rules for creating Action method
-> Action method should declare as “public” access specifies.
->It should not be private static mvc execution process.
Execution process Asp.Net mvc application
Q. Explain the execution process Asp.Net mvc application?
Q. How to process the request in mvc application?
Q. Explain the request processing life cycle on mvc?
1). End user will make a request to mvc application using browser.
We need to enter URL to make a request.
http://sitename/Home/Index
http://sitename/Home/Login
2). Request will send to server based on the URL.
To transfer the request to sever, it will make use of http protocol.
Once the server receives the request server will hand over to mvc engine.
3). In this step mvc engine will process rout configuration.
At this stage it will verify route format.
It is first time it will configure route format, default values.
4). In this step, MVC engine will load controller class form Application DLL.
(mvcApplication.dll).
It requested controller class is not available accessible, It will given 404 error.
5). In this step mvc engine will create instance for requested controller class.
6). Action method will invoke with the help of controller class instance.
In this step action method will be executed
Action method contains the logic how to process the request.
7). Action method may contain the logic to communicate with model.
In this step, model Executes corresponding logic to perform database operation.
Model will send the result back to action method.
8). After action method execution view page process will started.
It will performed by view engine (Razor).
View engine is capable of executing both html and c#.
9). After execution view peg it will generate html formed output.
Browser can support all html formats.
In this step html formatted output will send to controller.
10). After receiving the output, controller will send back to browser as response.
Browser will display the output to end- User.
Mvc Application class
-> MVC Application organizes its class according to folder structure.
->It maintains separate folders for controller models etc.
->It generates separate namespace for every folder.
-> E.g.: MVCApplication. Controller
->It wants to access the class of one namespace into another we have to import corresponding namespace.
-> Suppose if we want to access models class in controller we have to import “mvcappliction. Models” namespace.
View in mvc Application
-> In MVC V stands for “Views”.
-> Views are responsible for presentation logic.
-> It will take of presenting data to end user.
-> View are playing very important role in mvc application development.
-> End-User will communicate with the output which returns by view.
-> View should be understandable by end-user.
->At the time of creating the view we may display the data in data in the form of :-
(i) Paragraphs
(ii) Lists
(iii) Tables
(iv) Charts
->Most of the action methods in controller return the views as result.
->Every action method will contain the corresponding view.
Q. What are technologies used to developing view?
Ans: - views are develops with help of following techniques:
i) C# code
ii) HTML tags
iii) CSS(for styles)
iv) JavaScript
v) jQuery
Q. How to adding views?
-> Use the following steps to adding views
-> Open controller.
-> Right Click on Action method
->Add View
->Click “Add” button.
[OR]
-> Open solution explore.
->Right click on “Views “load of subfolder” folder.
->Add view
->Provide view name
->Add “click” button.
Note: - 2nd options are used to files to “shared” folder.
->”shared “folder is sub-folder of “views”
Generally “shared” folder contains special files like
Layouts
Partial views
Folder strutucter of views in mvc application
->The view files in mvc application or organized with the special folder structure.
-> It will maintain separate folder for ever controller.
-> When we are adding view if will creates corresponding folder under view folder.
-> It the folder already exist we simply add view field t corresponding folder.
Note: - The folder names under views are based on the controller name (without controller lost fire).
-> The views folder is having an additional sub folder called shared which contains reusable files across all other views.
View Engine in MVCApplication
Q. What is view Engine?
-> View Engine is sub-system of mvc framework.
->View Engine is responsible for executing the view.
->View Engine executes the view page separately from the main execution process.
->Asp.Net supports multiple views Engine.
Q. What are views Engine available for MVC Applications?
(1) Aspx (Web Form)
(2)Razor
-> We many also use third party view engines.
E.g.: - spark, nhaml, etc
Note:-
->Among the above view engines, Razor is the default and best view engine.
-> Most of the developer are using Razor view engine.
->Razor view engines are introduced in ASP.Net mvc.
Razor View Engine
->Razor view Engine is the default view engine for all mvc application from version 3.0.
->It is advanced new engine.
->It cans automatically identity server items and client items.
->All razor view files having extension
CSHTML/VBHTML.
*.cshtml
*.vbcshtml
Note:-Same extension for regular views, layout, view, partial view etc..
Advantage of Razor
->Easy to write the code.
->Less no. of characters to type.
->More comfortable.
->Easy for unit testing.
Programming views using Razor
->Add->controller->name->Home controller
->Razor provides is following swap of including server item in view pages.
1. Single line statement
2. Multiline statement
3. In-line statement
->We can use above statement in add server code in view pages.
-> “@” symbol in Razor adenitis as server items.
Single line statement
->If our code is required to prepare with single line we can this option.
Ex. @ {string name=”Scott” ;}
Multiline statement
->If we want to prepare more than one line, we can use multiline statements.
->Multiline statements also called as “Razor blocks”
E.g. @ {
int n=10;
n=n+10;
}
In-line statement
->If we want to use server programming variables with in html tags, we can use this option.
E.g.:- <h1>Welcome to @uname</h>
Note:-
->It we want to include any expressions in in-line statement keeps it in brackets.
E.g.
<h1>The value of n :< /h1>
@ (n+1) </h>
->If we want to print @as output, we have to use @@
E.g.:- <h1>contact me @7pm</h>
Razor comments
@*
Comments
*@
->Email id will automatically detect by razor.
Example
Create a view page to demonstrate usage razor statements.
Index.cshtml
@*single-line statement*@
@ {string uname =”mithilesh”;}
@*Multiline statement*@
@{
int n=10;
n=n+10;
n=n+20;
Response. Write (“value of n:”+n);
}
@*in –line statement*@
<h1>Welcome to @uname</h1>
Ex:-.
Create view tags display student information.
(1) Create MVC Application and HomeController.
(2) Add view for index () action method.
(3) Prepare the view page as follow.
(4) File name : Index.cshtml
Index.cshtml
@{
int son=1025;
string sname=”Scott”;
string cname =”Asp.Net mvc”;
}
<br/>
<h2>Student Id: @sno</h2>
<h2>Student name: @snname</h2>
<h2>Student course Name: @cname</h2>
EX:-
Create a view page to display list format
Index.cshtml
@{
string[] arr={“ASP.NET”,”ASP.NET MVC”,”HTML”,”CSS”,”XML”,”JavaScript”,”JQuery”,”HTML5”,”CSS3”};
}
<br/>
<ol>
@{
foreach (string item in arr)
{
<li>@item</li>
}
</ol>
Or
For (int i=0; i<arr.Lenth; i++)
{
<li>@arr[i]</li>
}
Ex
Create a view page to display course name using list class.
// Collection Initializier.
List<string> csList=new List<string>()
{“ASP.NET”,”ASP.NET MVC”,”HTML”,”CSS”,”XML”,”JavaScript”,”JQuery”,”HTML5”,”CSS3”};
}
<h2>Course names with List class </h2>
<hr/>
<ol>
@{
foreach (string item in csList)
{
<li>@item</li>
}
</ol>
Processing submitted (posted) values in views
In web Application request are categorized into two types.
(1) Get Request.
(2) Post Request.
-> In request can be made by enter the URL in address bar or by click hyperlink.
->Generally first request is always consider as GET request.
-> Post Request can be made by click submit button.
-> This request can be implemented by using JavaScript submit () method.
-> Most of the examples post request is actually contains values to process.
Note:
-> At the time of click submit button only the control values will post to server.
-> We should place all the controls with in <form> tags.
-> If we want to access values, we have to use “Request” in server code.
Ex.
Create a view page welcome massaged based on the given user name.
<form action=”/Home/Index” method =”post”>
Enter your name:
<input type=”text”,
Name=”t1”,
Id=”t1”/>
<br/>
<input type=”submit”,
Name=”sb1”,
Value=”Get Message”/>
</form>
@{
If (IsPost==true)
{
String uname=Request [“t1”];
<h2>This is post request </h2>
<h1>Welcome to @Uname</h1>
}
else
{
<h2>This is Get request</h2>
}
}
ISPOST Propertity
-> It is a bool property.
-> It returns:
True->for POST request
False->for get request.
->This property available in view page server program.
Uses:
If (IsPost==true)
{
//logic for post request
}
How to read the values submitted in post request?
-> We can read the values from POST request by using a “Request” object.
-> It is a predefined object to read to the values from requested submitted by browser.
->Request object stores the values in the form of key-values:
Key – name of the input control.
Value-value that is available in the input control
Uses:
String str=Request [“t1”]
Note:-
Request object returns the values in string format.
HTML Helper class
-> We can prepare html controls by using <input/> tag
->It is manual approach.
-> Razor view engine will send these input tags as response.
->Apart from the manual approach mvc framework provides special class called “HtmlHelper”.
-> By using HtmlHelper we can easily creates html controls in views.
->Every view page that we are preparing uses internally a class’s called Web view page.
->Web views peg object provide object called “HTML”.
-> By using this “HTML” we can create all html control.
Eg. Html.TextBox (“text1”);
Note:-
è Every helper method will return a string which corresponding input tag.
Html.TextBox (“text1”)
<input type =”text”
Id=”text1”/>
è Html helper method does not support button controls.
è Html Helper methods are not server controls if just reduce the coding burden on programmer.
List of Helper methods
1. BeginForm()
2. ActionLinl()
3. Textbox()
4. Password()
5. TextArea()
6. RadioButton()
7. CheckBox()
8. ListBox()
9. DropDwonList()
10. Hidden()
11. Label()
Note:
è Use the following system to prepare from tag:
@using (Html.BeginForm ())
{
}
è If we are not provide any argument for BeginForm () it will submit controller.
è If we want to specify we can provide the values as follows:
Html.BeginForm (“ActionMethodName”,”ControllName”, FormMethod.post)
Eg:-
Html.BeginForm (“Index”, “Home”, FormMethod.post)
Example
->Create a view page to prepare login functionality
1. Create mvcApplication and add HomeController.
2. Add Login () action method.
Public ActionResult Login ()
{
}
3. Add view page for Login () action and prepare as follow.
Login.cshtml
<h2>Login Page</h2>
<hr/>
@using (html.BeginForm (“Login”, “Home”, FormMethod.post))
{
@Html.Label (“Enter User id”)
@html.TextBox (“Uid”);
<br/><br/>
@Html.Label (“Enter password”)
@Html.Password (“pwd”)
<input type =”submit” value=”Login” name=”sb1”/>
}
@{
If (IsPost==true)
{
string s1=Request [“Uid”];
string s2=Request [“pwd”];
if (s1==”admin” && s2=”admin123”)
{
<h1 style=”color: green :”> welcome to s1</h1>
}
else
{
<h1 style =”color: red”>Invalid UserId or Password </h1>
}
}
}
Example-2
Create Department data for inserting
Details.chhtml
<h2>Department Details</h2>
<hr/>
@using (html.BeginForm (“Show Details “,”Home”, FormMethod.post)
{
@Html.label (“Department id”)
@Html.TextBox (“Did”)
<br/><br/>
@Html. label (“Department Name”)
@html.TextBox (“DName”)
<br/><br/>
@html.label (“Location”)
@Html.TextBox (“DL”)
<br/><br/>
Ex. Create a view page to display Employee count best on the given department.
Index.html
@using System.Data.SqlClinet
<h2>Department Details<h2>
<hr/>
@using (html.BeginForm ())
{
@html.Label (“Enter Dept Number :”)
@html.TextBox (“Deptno”)
<br/><br/>
<input type=”submit” value=”Get Emp Count” name=”sb1”/>
}
@{
If (IsPost==true)
{
String s1=Request [“Dept No”];
String constr=”server=”mithilesh” Database=”MVCDB” User Id=sa; Password=12345;”
String CmdText=”Select Count (*) from EMP Where DeptNo =”ts1”;
SqlConnection con=new SqlConnection (constr);
SqlCommand cmd=new SqlCommand (CmdText, con);
con.open ();
Object obj=cmd.ExecuteScaler ();
con.Close ();
<h1>Employee count:@obj.ToString ()
</h1>
}
}
Action method parameters
->In order to process the get request and post request separating we need to prepare different action method.
-> By default same action method will execute for both requests.
-> It is required to prepare different action method so that we can organize the logic efficiency.
-> Mvc framework will require the action method base on the attribute.
->In we want to prepare separate action method for post request, mark that method with [HttpPost] attribute.
Ex:-
[HttpPost]
Public ActionResult Index (args)
{
//Post request Logic
}
-> Generally post method will process the values submitted by user.
->In order to receive these values in action method mvc framework provides the following options.
1. FormCollection
2. Form Parameters.
FormCollection
-> MVC framework provides the formCollection to handle the action method parameters.
-> If can store all request object values as a collection.
-> It is almost same as the Request Object.
->It stores the data key-values pair Format.
->Key-name of the input control.
-> Value-data in the input control.
Uses:
String str=frmObj [“key”]
Note: - if Returns the values in string format.
> If is easiest way to different get/post action methods.
Implementation
[HttpPost]
Public ActionResult Index (formCollection frmObj)
{
//Post request logic
}
Example
Create a MVC Application to perform same operation by using “formCollection” parameters in Action method.
1. Create MVC Application and Add HomeController.
2. Prepare the action method as follows.
HomeController.cs
Namespace mvcApplication.controller
{
Public class HomeController
{
Public ActionResult Index ()
{
Response.Write (“Hello world form Get Request”);
Return view ();
}
[Http Post]
Public ActionResult Index (FormCollection frmObj)
{
Response.Write (“Hello world from post Request”);
Int x=int.Parse (frmObj [“t1”]);
Int y=int.Parse (frmObj [“t2”]);
Int z=x+y;
Response.Write(“<br>sume Result:” + z);
Return view ();
<h2>Index page<h2>
<hr/>
@using (Html.BeginForm ())
{
@Html.Label (“Enter First number”)
@Html.TextBox (“t1”);
<br/><br/>
@Html.Label (“Enter second number :”)
@Html.TextBox (“t2”)
<br/><br/>
<input type=”submit” name3=”sb1” value=”Sum”/>
Note:
(For FormCollection)
-> At the time of reading values from formColletion object key should be same as textbox name.
Formal Parameter
-> Mvc Framework provides another option to handle parameter easily.
->It is called “Formal parameters”.
->We can directly specify required no of parameters with prepare data type in Action method.
->In these option action method parameters names should same as textbox name.
->At the time of execution controller will perform.
-> Reading the values from request.
->Type casting
-> Send to action method
Usage
[Http Post]
Public ActionResult Index (int t1, int t2)
{
//logic
}
Example
Update the previous example post action method
First method is same as previous example.
[Http Post]
Public ActionResult Index (int t1, int t2)
{
Response.Write(“Hello world from POST Request”)
Int z=t1+t2;
Response.Write(“<br>Sum Result:”+ z);
Return view ();
}
Model Class Object
-> To perform database operations we need to get more values from user.
-> To implement this requirement formCollection does not support automate type casting.
->If we use formal parameters, we need to process more values in method parameters.
Solution: Model class object
-> We can manage multiple parameters with single object by using model class object.
->It also supports automatic type casting.
->Controller is responsible for creating setting values to properties send to action method.
Condition: Names of the textbox should be same as model class properties names.
Uses:
Public ActionResult Index (Dept obj)
{
//required logic
}
Add
Right click of model-> Add “class” write name “Dept.cs”
Example
Create mvc Application to process Dept details by using model class object as Action method parameter
1. Create mvc application and Home controller.
2. Add Dept class to “Models “folder.
->Go to solution Explore.
-> Right Click “Model” Folder.
-> Add -> class
File name: Dept.cs
3. Writing Dept Details
Dept.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace mvcApplication.Models
{
public class Dept
//Auto implemented properties.
Public int Deptno {get; set ;}
Public string Dname {get; set ;}
Public string Loc {get; set ;}
}
}
6. Add required Action method in HomeController.
HomeController.cs
Namespace mvcApplication.Controller
{
Public class HomeControler: controller
//Get Request
Public ActionResult index ()
{
Return view ();
}
post request
[Http Post]
Public ActionResult Index (Dept obi)
{
Response.Write(“<br>Deptno:” + obj.Deptno);
Response.Write(“<br/>Dname:”+Obj.Dename;
Response.Write(“<br/>Loc:” + Obj.Loc);
}
}
Index.cshtml
<h2>Department Details<h2>
<hr/>
@using (Html.BeginForm ())
{
@Html. Label (“Deptno :”)
@Html.TextBox (“Deptno”)
<br/><br/>
@Html.Label (“Location :”)
@Html.TextBox (“Loc”)
<br/><br/>
<input type=”submit” name=”sb1” value=”submit” dept Details/>
}
<hr/>
Emp.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace mvcApplication.Models
{
Public class Emp
{
Public int EmpNo {get; set ;}
Public string EmpName {get; set ;}
Public string Job {get; set ;}
Public int sal {get; set ;}
Public int DeptNo {get; set ;}
HomeController
using mvcApplication .Model
namespace mvcApplition.controller
{
Public class HomeController: Controller
Public ActionResult index ()
{
Return view ();
}
[Http Post]
Public ActionResult Index (Emp ob)
{
Response.Write(“<br/> EmpNo”+obj.Empno);
Response. Write(“<br/>EmpName”+obj.EmpName);
Response. Write (“<br/>Job”+obj.Job);
Response. Write (“<br/>Emp Salary”+obj.sal);
Response. Write (“<br/>DeptNo”+obj.DeptNo)
<h3>Employee Details</h2>
<hr/>
@using (Http.BeginForm ())
{
@Html.Label (“EmpNo”)
@Html.TextBox(“EmpNo”)
<br/><br/>
@Html.Label (“EmpName”)
@Html.TextBox(“EmpName”)
<br/><br/>
@Html.Label (“Job”)
@Html.TextBox (“job”)
<br/><br/>
@Html.Label (“sal”)
@Html.TextBox (“sal”)
<br/><br/>
@Html.Label (“Deptno”)
@Html.TextBox (“DeptNo”)
<br/><br/>
<input type=”submit” name=”sb1” value=”submit in the value”>
<hr/>
Sharing data between controller to views
-> Action method in Controller will process the request.
-> After processing the request results will be ready in action method.
->To display these result to end user we need transfer then to views.
-> Mvc framework provides the following option to transfer data between
Controllers to view.
1. ViewData
2. ViewBag
3. TempData
4. Strongly Typed views
ViewData
->ViewData object is used to sharing data between controls to views.
-> If stores the data in the form of key-values pairs format.
-> Key-string
->Value-object
-> ViewData is an object of ViewData Dictionary class.
-> We need to perform unboxing into appropriate type at the time of reading data from ViewData.
Uses
ViewData [“key”] =value;
ViewData [“age”] =25;
Int age = (int) ViewData [“age”];
ViewBag
-> ViewBag concept is introduced in mvc 3.0 version.
-> If is also similar to ViewData except typecasting.
-> If uses dynamic typing. If decides the type at runtime based on the value.
->Uses of keys properties.
Uses:
ViewBag.key=value;
ViewBag.age=25;
viewBag.name=”Mithilesh”;
int n=ViewBag.age;
String name=viewBag.name;
Note:
-> ViewBag is also uses ViewData Dictionary class at the time of process the data.
->ViewBag and view Data both objects scope is within the request.
-> After completion of execution of the action method and view these object will be classes.
Example
Create mvc application to demonstrate uses of options that are used to transfer data from controller to view
1. Create mvc Application and add HomeController.
2. Prepare the following action method in HomeController.
HomeController.cs
Namespace mvcApplication.Controller
{
Public class HomeController: Controller
{
Public ActionResult Index ()
{
Return view ();
}
Public ActionResult sum ()
{
Return view ();
}
[Http Post]
Public ActionResult Login (string uid, string pwd)
{
If (uid==”admin” && pwd==”admin123”)
{
TempData [“uname”] =uid;
Return RedirectToAction (“Index”);
}
else
{
viewBag.ErrorMessage=”Invalid userId and password”;
Return view ();
}
}
}
}
Required to view page
Sum.cshtml
<h2>sum operation</h2>
<hr/>
@using (html BeginForm ())
{
@Html.Label (“Enter first value”)
@Html.TextBox (“x”)
<br/><br/>
@Html.Label (“Enter second value”)
@Html.TextBox (“y”)
<br/><br/>
<input type=”submit” name=”sb1” value=”sum”/>
}
<hr/>
@{
Int n= (int) ViewData [“Result”];
<Span>sum Result:@n</span>
}
}
Loing.cshtml
<h2>Login Page</h2>
<hr/>
@using (Html.BeginForm ())
{
@Html.Label (“UserId”)
@Html.TextBox (“uid”)
<br/><br/>
@Html.Label (“Password”)
@Html.TextBox (“pwd”)
<br/><br/>
<input type=”submit” name=”sb1” value=”Login”/>
}
<hr/>
@{
If (IsPost==true)
{
String str=viewBag.ErrorMessage;
<span style=’color: red ;”> @str</span>
}
}
Index.cshtml
<h1>Index Page</h1
<hr/>
@{
String str= (string) TempData [“uname”];
<h1>website to @str</h1>
}
Update default route details in RouteConfig.cs
APP_Start/Routeconfig.cs
Action=”Login”
Note:
->RedirectAction () method is used to Redirective to from one action to another action.
-> This method to returns objects of RedirectToResult class.
-> RedireToResult class these also child class of action result.
TempData
->TempData is also similar to view data. It is used to transfer the data from one action to another action at the time of redirection.
-> TempData also starts data in the form of key-value pair format.
->Key data type is string.
->Value data type is object.
->TempData is an object of TempData dictionary class.
TempData [“uname”] =”mithilesh”;
String str= (string) TempData [“uname”];
Note
1. TempData words only when we more from one action one action method to another action method through redirection. It will not work in the case of hyperlinks. If we have from one page to another by clicking hyperlink.
2. Uses of RedirectToAction() method RedirectToAction(“Action Name”)
Ex: RedirectToAction (“Index”)
RedireictToAction (“Index”,”Emp”)
3. Problem with ViewData, ViewBag, TempData.
ViewData/TempData:
Need to perform type casting
ViewBag
Does not support intelligence.
Strongly Typed views
->Strongly typed views concept is designed to process model class data.
-> If support intelligence and with proper type. No need to perform Typecasting.
- This concept is very useful at the time of process database related information with model class object.
->Scaffolding TempData concept in mvc is completely works based on this concept.
Implementation
-> To implementation strongly typed view use the following steps:
1. Prepare data that we want to transfer from action method to view.
2. Send the data through view () method.
3. Specify the type of data that we send through view () method.
4. Access the data in view page by using “model” property.
5. “Model” is built property in view pages.
6.”model” property type will be decided based on step3
Eg:-step1
Int count =123;
step2
Return view (count)
step3
@model int
step4
<span>count:@model</span>
Ex:-
Create mvc Application to transfer count (int) from controller to view by using strongly typed view control.
HomeController.cs
Public ActionResult Index ()
{
step1
Int count =123;
step2
Return view (count)
Index.cshtml
step3
@model int
step4
</span count:@model</span>
HomeController.cs
public ActionResult course ()
{
step1
List<string> csList=new List<string>()
{“ASP.NET”,”ASP.NET MVC”,”HTML5”, “CSS3”,”JQUERY”};
Return view(csList);
}
Courses.csHtml
step3
@model List<string>
<h2>course name</h2>
<hr/>
<ol>
step4
@{
foreach(string item in model)
{
<li>@item</li>
}
}
Ex:-
Display Department by using strongly type concept:-
Step1
Dept d1=new Dept();
d1.DeptNo=10;
d1.Dname=”Account”;
d1.Loc=”Hyd”;
Step2
Public ActionResult Dept()
{
Int DeptNo=10;
String Dname=”Account”;
String Loc=”Hyd”;
Return view(DeptNo,Dname, Loc)
Index.cshtml
@Model int
@Model string
@Model string
<span>Deptno:@Model</span>
<span>DName:@Model</span>
<span>Loc:@Model</span>
-> Controller->Add->class->Dept.cs
Using mvcApplication
Namspace--------
{
Public --------
{
{
}
Public ActionResult Details ()
{
Dept d1=new Dept();
d1.Deptno=10;
d1.Dname=”Account”;
d1.Loc=”Hyd”;
Details.cshtml
@usnig mvcApplication.model
@model Dept
<h1>Department details<h1>
<hr/>
<span>DeptNumber:@Model.DeptNo</span>
<br/>
<span>DeptName:@Model.DeptName</span>
<br/>
<span>Location:@Model.Loc</span>
<br/>
HomeController
Public ActionResult Details()
{
Dept d1=new Dept();
d1.DeptNo=10;
d1.Dname=”Account”;
d1.Loc=”Hyd”;
return view(d1);
}
}
IEnumerable
->IEnumerable is a predefined interface in .Net.
->All collection class in .Net are implements “IEnumerable” Interface.
->This interface provides require functionality to read the items from collection using foreach.
->In strongly typed views preparation we can mention the type of data with its type or any of the base type/interface.
@Model int
@Model object
@Model List(Dept)
@Model IEnumerable<Dept>
GET Request Action method parameters
-> Action method for get request is also receiving the parameters.
-> Generally these values are available along with url.
-> To receive these values mvc framework provides two option
1. Query String
2. Route parameter
1. Query String
-> Query Sting concept same as in Asp.Net.
-> Attach the required values with url.
Eg.
/Home/Details?deno=10
/Home/Details?empNo=12
/Home/Browse?Category=Mobiles.
->To receive these values action method need to be prepared with format parameters.
Public ActionResult Details(int dno)
Public ActionResult Details(int Ename)
Public ActionResult Browse(string Category)
2. Route parameters
->Route parameter is related route format of MVC Routing concept.
-> In RoutConfig.cs route url is format as follows.
“{controller}”,” {action}/ {id}”;
-> In this format,”id” is called route parameters.
-> We send the values to get request by using this route parameter(id)
Eg:-
/Home/Details/10
/Home/Details/1234
->To receive the route parameter in action method , if should be prepare with id parameter
(1). Public ActionResult Details(int id)
(2).public ActionResult Details(int id)
Models in mvc
-> In mvc stands for models.
->Model contains database related logic.
->Models are responsible to communicate with database.
-> Every technology uses its own concept to communicate with database.
E.g.:- ASP.Net mvc
ADO.NET
Entity framework
Java(struts/spring)
Hibernate
JDBC
Model classes
We are implementing models concept by define required classes.
->These classes are divided into two types.
1. Entity class
2. Datacontext class.
No comments:
Post a Comment