MVC by RN Reddy-Rnrits
MVC by RN Reddy-Rnrits
REDDY
Step by
Step
ASP.Net MVC
by
Mr.R.N Reddy
RN Reddy IT School
Online/Classroom Training’s |Work Supports |Proxies
For more details
E-Mail: [email protected]
Phone : +91 9966640779, 9866183094,9885199122
Visit: www.rnreddyitschool.co
FB Page: - www.facebook.com/Reddyitschool
1|Page
ASP.NET MVC MR.R.N.REDDY
Cover’s:-
------------
1. ASP.Net MVC
2. Linq
3. Entity Frame Work
4. Bundling In MVC
5. Routing In MVC
6. Filter In MVC
Introduction To MVC
2|Page
ASP.NET MVC MR.R.N.REDDY
Architecture:
Web Forms MVC
ASP.NET
Model:
3|Page
ASP.NET MVC MR.R.N.REDDY
View Model
4|Page
ASP.NET MVC MR.R.N.REDDY
5|Page
ASP.NET MVC MR.R.N.REDDY
6|Page
ASP.NET MVC MR.R.N.REDDY
Asp.Net
C#.NetVB.NetC++.Net
Note: Asp.Net Mvc is not replacement of Asp.Net ,if is on alternative option to develop web
application in .net environment finally we can say Asp.Net Mvc is next generation of Asp.Net web
forms.
Asp.Net Mvc application development environment:
Asp.Net Mvc provides two types of projects templates to develop the web application.
1.Main template:
Asp.Net Mvc4 web application.
2.Sub template:
1. Empty
2. Basic
3. Internet applications
4. Intranet applications
5. Mobile applications
6. Web API etc...
1.Empty:
This template is similar to Asp.Net empty web applications.
its generates empty folders. We need to develop form scratch.
2.Basic:
This template same as empty template.
It provides additional folders for client side programming.
I. Content:- this folder can contain .CSS files and Images.
Example: .CSS
II.Scripts:- this folder can contain the client side scripting like
Java Script , Angular JS, or J Query files ...
Example: .Js
3.Internet applications:
This template is same as “Asp.Net” web application.
7|Page
ASP.NET MVC MR.R.N.REDDY
1.App_start:
This folder content application start up setting related files. These files are C# files(.CS)
By default this folder will come with four C# file
1. BundleConfig.Cs
2. FilterConfig.Cs
3. RouteConfig.Cs
4. WebApiConfig.Cs
Among these 4 files important file is routeconfig.cs
In this file we will defined the default controller details.
2.Content:
Content folder contains all ‘css’ files,we may add images also in this folder if we required
3.Controller:
Controller folder contains all controller class files.
8|Page
ASP.NET MVC MR.R.N.REDDY
It will open Add controller window here rename controller name as HomeController, Click
Add button with this one controller is Added.
i.e. HomeController.Cs
We can add multiple controllers but every controller file will be C# class file.
Extension will be .Cs
4.Models: This folder contain database logic related C# files.
Here we will implement Ado.Net code or Entity Framework code.
5.Script: It contain client side scripting file(.Js)
For ex: .Js
By default Asp.Net Mvc project generates JQuery related files
We can also add user defined script files in this folder.
6.Views: views folders contain webpage.
In Asp.Net Mvc all web pages are HTML web pages.
In Mvc user develop with C# code and HTML tags,due to that reason these files extension
will be like below
“.Cshtml”
Note: Asp.Net Mvc application follows proper folder structure, you should add the file in
specified folder only.
Controllers in Asp.Net Mvc :-
In Mvc 'C’ stands for controller .
Controller is responcible for application execution logic.
Controller is important module in Mvc which will take care execution on every
request.
In Mvc applications request or handled by controller.
Every request in mvc application mapping with controller and corresponding action
method.
Controller is act as a mediatory between model and view. That model communicate
with view throw controller.
9|Page
ASP.NET MVC MR.R.N.REDDY
Object I Controller
Controller Base
Controller
Home Controller
Note:Here controller class and controller base class are predefined abstract class.
But I-controller is predefined interface.
10 | P a g e
ASP.NET MVC MR.R.N.REDDY
Action Method:
Controller will process the request with the help of action method.
Actual action method contains request processing logic
This logic may communicate with model to process database related task.
Action method will prepare the result that should display in view.
Finally action method will transfer the result to view in order to display to end user
11 | P a g e
ASP.NET MVC MR.R.N.REDDY
}
Class contentResult:ActionResult
{
}
Class JSonResult:ActionResult
{
}
Class FileResult:ActionResult
{
}......
In mvc Action()Method may return any type of above result class type:
But Action Result class variable can hold any of the above result class objects. Because
action result is the super class for all above result class.
A diagram to represent how view result object is holding by the action result class variable
like below.
Null
1010
1010
Type of ActionMethods:
12 | P a g e
ASP.NET MVC MR.R.N.REDDY
The method which we will define with in the controller are called ActionMethod. These
ActionMethods are 3 types:
1. Action method with ViewResult.
2. Actiom method with non ViewResult.
3. Non-Action method.
Action method with ViewResult:
ActionMethod that will return View pages output those method come under.
Most of the actionmethod() or returnview result.
These method return statement like below.
ReturnView().
These method requided a view page with corresponding method name
For ex: index.cshtml.
Action method with non view result:
Action method with non view result.
Action method will return data instated of HTML formatted output(webpage)
These method will return single value/object /collection of objects.
Especially in Ajax programming we are involving these methods.
These method having return statements like below
1. Return JSon();
2. Return content();
These method doesn’t required view page.
Non_ActionMethod:
By default all method in controller class consider as action method.
All action methods can be accessible(requested) by end user from browser.
If we want to define a method that should access with be called as non_action
method.
Note: Non_action methods are preparing by using a attribute like below.
That is: [Non Action]
13 | P a g e
ASP.NET MVC MR.R.N.REDDY
At the time of appling attribute we will write particular attribute with in[].
For example:
[NonAction]
[HttpGet]
[HttpPost]...
We can apply attributes either to define class or methods or property.
For example:
[NonAction]
Public int sum[int x, int y]
{
Return x+y;
}
View in Asp.Net Mvc Applivation:
In mvc application,execution of views are processed by a special view engine called view
enginee.
What is view enginee?
view engine is sub system of Mvc framework.
View engine can independent process the views.
If any changes in view page no need to compile entire project.
Views are separately process by view engine.
What are the view engines supported by Asp.Net Mvc ?
Microsoft has developed two view engines that are integrated with Asp.Net Mvc
1. Web form view engine [.aspx].
2. Razor engine.
1.Web form view engine [.aspx]:
Web form view engine is introduced in Asp.Net Mvc 1.0
It uses same style of Asp.Net web forms.
Limitations of web form view engine:
Write server code(C# code in aspx.file is complex)
It is not much comparable for programmers to perform development, modification ,
testing.
We need to write more code to organize server logic.
2.Razor engine:
Razor engine was introduce in Asp.Net Mvc 3.0.
Razor engine called advanced view engine.
Compare with Aspx view engine razor engine will provided more advantages.
Advantages of Razor engine:
less code to implement server side logic.
Razor engine is having automatic recognition of C# statements and Html tags
because it is advance view engine.
Easy to perform unit testing and more comfortable for development and
modification.
Which contain mixing of Html and C# code.
Easy to read and understand.
Basic of Razor programming:
In razor programming view page execution will be .cshtml.
Every view page(.cshtml) contain html tags and C# code.
14 | P a g e
ASP.NET MVC MR.R.N.REDDY
Example:2
<span>EmpName is: @obj.Ename</span>
O/P
---------------------------
Empname is:Ravi
Example:3
<span>Custname is: @obj.cname</span>
O/P
------------------------------
CustName is:raju
Example:4
Int i=10;
<span>@(i+1)</span>
O/P
--------------------------
11
SingleLine Statement:
If we want to write one line of C#.code then we can use this option.
If may be used to declare variables/objects,assignments,statements...
Syntax:
@{C#statements}
For example 1:Declare a variable:
@{int x=10;}
15 | P a g e
ASP.NET MVC MR.R.N.REDDY
MultiLine Statements:
If we want to write more than one Line of C# code then we can used the option.
Multiple statements also allow the html tags.
Razor engine automatically deviate C# statement and Html tags.
Example for MultiLine statements:
@{
Int x=10;
If(x%2==0
{
<h1>@x is Even</h1>
}
Else
{
<h1>@x is odd</h1>
}
}
Note:
where we will write the server side logic. that is: C# code in case of web form view engine.
A. With in .aspx file head session.
Programming by using Asp.Net Mvcwith the help of web from view engine.
Who will select the view engine?
A. Programmer
1.example to display one welcome message with the help of web form view engine in
step-by-step:
step 1: Open Visual Studio .Net.
click on new project it will open new project window,here select visual C# and select
web,right side select Asp.Net Mvc4 web application and rename it as:
MvcEmptyWelcomeApp click OK.
It will open New Asp.Net Mvc4 project then select a template called Empty, then select view
engine as aspx then click OK with this process a new Asp.Net Mvc empty Application will
create.
Step 2: Adding Controller.
Open solution explorer select controller folder right click Selec Add Controller. with
this process add controller window will open.Rename it as HellowWordController Click
Addwith this process a new controller will add to the controller folder that controller name
is HellowWordController.Cs .
By default HellowWordController.Cs will come with one action method.
That is: Index().
Finally .Cs file will be like below.
Class HellowWordController:Controller
{
Public ActionResult Index()
16 | P a g e
ASP.NET MVC MR.R.N.REDDY
{
Return View();
}
}
Example to display the welcome message using aspx view engine when the page is loading.
Step:1 Gating a new empty application.
Step:2 Adding Controller.
Step:3 Adding view page to controller
Step:4 Add design code(Index.aspx) div session
Note: no design code.
Step:5 write the server side code(C# Code) in Index.aspx Headsection.
Here we need to load event due to that reason double click on Index.aspx page to generate
load event .
<script runat=”server”>
Void page_load()
{
Response.write(“HI , Welcome to Asp.Net Mvc”);
}
</script>
17 | P a g e
ASP.NET MVC MR.R.N.REDDY
Step:6 Initialize the default controller within RouteConfig.CS Build the solution and run the
application, finally O/P is Index.aspx
Hi, Welcome to Asp.Net Mvc
Example to display the welcome message within the label at the time of page is loading by
using Aspx View Engine.
Step:1 Create a empty Mvc application.
Setp:2 Adding a Controller.
Step:3 Adding a view page to controller.
Step:4 Adding the design code within Index.aspx div selection.
<div>
<asp: Label ID=”lblwelcome” runat=”server” />
</div>
Setp:5 Write the server side code i.e C# code in Index.aspx head session.
<script runat=”server” >
Void page_load()
{
Lblwelcome.Text=”welcome to Asp.Net Mvc...”;
}
</script>
Build and execute the O/P is
index.aspx
Welcome to Asp.Net Mvc
Example to display to messages on web page within using label when the page is loading by
using aspx view Engine Application name MvcFirstApplication. Controller name is Welcome
view page name Home.aspx.
step1: Creating new MvcFirstApplication.
Select view Engine.aspx
Step2: Adding the controller WelcomeController.CS
Step3: Adding viewpage to the controller Home.aspx.
Step4: Adding design code(Home.aspx) div session
Note: No designcode.
Step5: write the server code(C# Code) in Home.aspx.here we need load event due to that
read on double click on the Home.aspx page to generate load event.
<script runat=”server”>
Void page_load()
{
Response.write(“I Like C#.Net”);
Response.write(“I Lile Asp.Net”)l;
}
</script>
Observation : Whenever we are implementing aspx view engine programming there are two
precutations we should take care.
1.Action method name and view page name should be same.
2.By default Action method name is Index().
18 | P a g e
ASP.NET MVC MR.R.N.REDDY
For example: If we want to be have view page as employe.aspx then ActionMethod name
should be changed as Employee()
When ever ActionMethod name should be changed then we should change the
RouteConfig.CS file below Attribute i.e. action=”Employee”
Example to implement aspx view engine programming by changing with action method
name as student() and view page name as student.aspx.
Step:1 Create asp.net Mvc application.
Step:2 Add controller rename it as myEmpController(every controller should postfix as
“Controller”).
Note: Here controller name is MyEmp display name is MyEmp controller
Step:3 Adding the view:
Open MyEmpController.Cs and change the action method name asstudent() like below:
Public ActionResult Student()
{
return view();
}
Right click on action method i.e. student()
Select Add View.
View name as student
View engine as aspx.
Unselect the master page checkbox.
Click Add Button in this process a new page will as
i.e. student.aspx under
View
Myemp
Student.aspx
19 | P a g e
ASP.NET MVC MR.R.N.REDDY
O/P is Student.aspx
Welcome to Asp.Net Mvc aspx programming
View
Welcome
[@]Display.Cshtml
Write the below code with in the Display.cshtml page div section Display.cshtl page
<html>
<body>
<div>
<h1>welcome to Asp.Net Mvc Razor programming</h1>
</div>
</body>
</html>
step4: Open App_start folder open routeconfig.cs file
change the controller =”Welcome ” action =”display”
step5: Build the solution and Run the application finally
20 | P a g e
ASP.NET MVC MR.R.N.REDDY
O/P Display.Cshtml
Example to display welcome message with the help of single line statement and inline
statement
Step1: creating the application
Step2: Adding the controller
Step3: Adding viewpage
Step4: write the below code with in Display.cshtml file
<html>
<body>
<div>
@{ String name = “Rama”;}
<h1> welcome to @ name</h1>
</div>
</body>
</html>
Example to implement multi line statement and inline statement
Step1: creating the application
Step2: Adding the controller
Step3: Adding viewpage
Step4: write the below code with in Display.cshtml file
<html>
<body>
<div>
@{ String name = “Rama”;
Byte age= 20;
String location =”Hyderabad”
<h1> welcome to @ name</h1>
<h1>age is @age</h1>
<h1>location is @ location</h1>
}
</div>
</body>
</html> O/P
Name is : Rama
Age is : 20
Location is : Hyderabad
21 | P a g e
ASP.NET MVC MR.R.N.REDDY
customer id is:111
22 | P a g e
ASP.NET MVC MR.R.N.REDDY
Example to calculate 6 product cost total bill i.e. p1 to p6 and on total bill give 10% discount
values and display total bill before discount and give discount value and after discount.
Dispaly.cshtml
P1 double p2 double p3 double
Total bill before is:21000
1000 20000 3000
Discount is:2100
p4 double p5 double p6 double
4000 5000 6000 Total bill after discount:18900
23 | P a g e
ASP.NET MVC MR.R.N.REDDY
Step2: <div>
@{
Int i=10;
Int j=10;
If(i > j)
{
<h1> i is greater than j<h1>
}
Else if(j > i)
{
<h1> j is greater than i</h1>
}
Else
{
<h1>i is equals to j</h1>
}
}
24 | P a g e
ASP.NET MVC MR.R.N.REDDY
</div>
25 | P a g e
ASP.NET MVC MR.R.N.REDDY
copy
Webform1.aspx
Post back request
copy
Post back request
submit Webfrom2.aspx
26 | P a g e
ASP.NET MVC MR.R.N.REDDY
Step:2 Write the below design code with in the body section of Index.cshtml
<html>
<body>
<form name=”myform” method=”post”>
<div>
<input type=”Submit” name=”btnsubmit” value=”Submit” />
</div>
</body>
</html>
Step:3 Write the Razor code with in the Index.cshtml
@{
Layout=null;
If(IsPost)
{
<h1> this is post back request </h1>
}
Else
{
<h1> this is first request</h1>
}
}
Example to accept two numbers and perform Addition then display the Addition request
a
10
Enter first number : 10 b
5 5
Enter second number:
c=a+b
10+5
Add
15
Result is: 15
27 | P a g e
ASP.NET MVC MR.R.N.REDDY
Index.cshtml [Designcode]
<div>
Enter first Number:<input type=”text” name =”txtnum1” />
<br/></br>
Enter second Number:<input type =”text” name=”txtnum2”/>
<br/>
<input type =”submit” name=”btnsubmit” value=”submit” />
</br>
Result is: <span>@c </span>
</div>
Step :3 Razor code with in index.cshtml
@{ layout=null;
Int c=0;
If(this.IsPost)
{
Int a=request[“txtnum1”].AsInt();
Int b=request[“txtnum2”].AsInt();
C=a+b;
}
}
Submit
Valid user
<br />
<input type="submit" name="btnsubmit" value="submit">
<br />
<br />
<spanp>@msg</spanp>
28 | P a g e
ASP.NET MVC MR.R.N.REDDY
</div>
</form>
</body>
</html>
Step 3: Razor code
@{
Layout = null;
string msg = Request["txtemaild"];
if(this.ispost)
{
if (Request["txtemaild"] == "[email protected]" && Request[“txtpwd”]=”sitha123”)
{
msg = " userId : " + msg;
}
else
{
msg = "invalide userid";
}
}
}
Implement above example with following validations
1.txyUname should not be empty.
2.txtpwd should not be empty.
3.txtUname should be Rama.
4.txtPwd length should be 6 characters.
5. txtPwd should be sitha123.
submit
Step 2:
what is the predefined method empty
IsEmpty()
This method will return true the given filed is empty otherwise it will return false.
What is the property you check the length field
By using a property called “Length”.
Index.Cshtml[design code]
<body>
<form name=”myform” method=”Post”>
<div>
Enter userid:<input type=”text” name=”txtuname”/>
<span>@uidmsg</span>
<br/>
29 | P a g e
ASP.NET MVC MR.R.N.REDDY
<br/>
Enter your password :<input type=”password” name=”txtpwd”/>
<span>@pwdmsg</span>
<br/>
<br/>
<input type=”Submit” name=”btnsubmit”/>
<br/>
<br/>
<span>@msg</span>
</div>
</body>
</html>
Step:4 Razor Code:
@{
Layaout=null;
String uidmsg=””;
String pwdmsg=””;
If(this.post)
{
If(Request[“txtuname”].IsEmpty())
{
Uidmsg=”*plz enter user name”;
}
Else if(Request[“txtpwd”].IsEmpty())
{
Pwdmsg=”*plz enter password”;
}
Else if(Request[“txtpwd.length”]<6)
{
Pwdmsg=”*password should minimum 6 characters ”;
}
Else if(Request[“txtuname”]==”Rama”&&Request[“txtpwd”]==”sitha123”)
{
Msg=”valid user”;
}
Else
{
Msg=”invalid user”;
}
}
Example to accept name and age from the user and display on demand with following
validations.
1.Name Should not be empty 2.name textbox should allow only letters
3.age textbox not be empty4.age textbox should allow only numbers.
rama
submit
31 | P a g e
ASP.NET MVC MR.R.N.REDDY
32 | P a g e
ASP.NET MVC MR.R.N.REDDY
Telugu
Hindi
English
Submit
Step2: index.cshtml[code]
<html>
<body>
<form name=”myform” method=”post”>
<div>
<h1>select your mother tongue</h1>
<input type=”radio” name=”language” id=”radioTelugu” value=”telugu”/>TELUGU
<br/>
<input type=”radio” name=”language” id=”radioHindi” value=”Hindi”/>HINDI
<br/>
<input type=”radio” name=”language” id=”radioEnglish” value=”English”/>ENGLISH
<br/>
<input type=”Button” id=”btnsubmit” value=”Submit”/>
</br>
<span>@msg</span>
</div>
</form>
</body>
</html>
Step:3 Razor code
@{
layout=null;
string msg=””;
if(this.Ispost)
{
If(Request[“language”].IsEmpty())
{
Msg=”*plz select your mother tongue”;
}
Else
33 | P a g e
ASP.NET MVC MR.R.N.REDDY
{
Msg=”your mother tongue is:”+Request[“language”];
} }}
Implement above example with out submit button
Step1:index.cshtml[design]
Telugu
Hindi
English
Your mother tongue is: Telugu
Step2: index.cshtml[code]
<html> <body>
<form name=”myform” method=”post”>
<div>
<h1>select your mother tongue</h1>
<input type=”radio” name=”language” id=”radioTelugu” value=”telugu”/>TELUGU
<br/>
<input type=”radio” name=”language” id=”radioHindi” value=”Hindi”/>HINDI
<br/>
<input type=”radio” name=”language” id=”radioEnglish” value=”English”/>ENGLISH
<br/>
<span>@msg</span>
</div>
</form>
</body>
</html>
Step:3 Razor code
@{
layout=null;
string msg=””;
if(this.Ispost)
{
Msg=”your mother tongue is:”+Request[“language”];
}
}
}
Example to select known languages by using check box control & submit button.
Step:1 Index.cshtml[Design]
Telugu 34 | P a g e
Hindi
ASP.NET MVC MR.R.N.REDDY
Submit
Step2: index.cshtml[code]
<html> <body>
<form name=”myform” method=”post”>
<div>
<h1>select your mother tongue</h1>
<input type=”checkbox” name=”language” id=”checkTelugu” value=”telugu”/>TELUGU
<br/>
<input type=”checkbox” name=”language” id=”checkHindi” value=”Hindi”/>HINDI
<br/>
<input type=”checkbox” name=”language” id=”checkEnglish” value=”English”/>ENGLISH
<br/>
<input type=”Button” id=”btnsubmit” value=”Submit”/>
</br>
<span>@msg</span>
</div></form></body></html>
Step:3 Razor code
@{
layout=null;
string msg=””;
if(this.Ispost)
{
If(Request[“language”].IsEmpty())
{
Msg=”*plz select your known languages”;
}
Else
{
Msg=”your know languages are :”+Request[“languages”];
}
}
}
Example to select the country by using drop down list & submit button
Step:1 index.cshtml[design]
35 | P a g e
ASP.NET MVC MR.R.N.REDDY
-select-
India
USA
UK
submit
36 | P a g e
ASP.NET MVC MR.R.N.REDDY
}
Implement above example with out submit button
Step:1 index.cshtml[design]
Select your country
222
India
USA
UK
Your country name : India
37 | P a g e
ASP.NET MVC MR.R.N.REDDY
2. AsDateTime()
3. AsDecimal()
4 As float()
5. As Int()
Razor comparison Methods
Razor programming will Sport followingcomparison methods
These methods will Compare the given Value, if the Value is matched then it will return
"True" Value otherwise it will return false value
1. ISBool()
2. IsDateTime()
3. IsDecimal()
4. IsEmpty()
5. Isfloat()
6.IsInt()
Web Forms Vs MVC: Asp.Net webforms Vs Asp.Net Mvc.
Here Asp.Net webforms is a Traditional web technology in .net
Asp.net Mvc is Advanced web technology in .net
In Asp.net webform we will have Serverside Controls as well as client side control but in
Asp.Net MVC we well have client side control.
In Asp.netwebforms webpage Extension will be .Aspx but in Asp.Net Mvc webpage
Extension will be .cshtml
A finally we can say asp.net is heavy weight programming but Asp.net mvc is light weight
programming & highly testable frame work.
Asp.net mvc will support all Executing Asp.Net webform features such as master page
Security & Authorization.
Age
20
38 | P a g e
ASP.NET MVC MR.R.N.REDDY
Rama
20
39 | P a g e
ASP.NET MVC MR.R.N.REDDY
View bag
Emp No is: 111
Eno
111
emp name is: Rama
Ename
emp salary is: 1000 Rama
esal
1000
Step 2:homeController.cs
Class HomeController
{
Public ActionResult Index()
{
Viewbag.eno=111;
ViewBag. Name="rama";
ViewBag.esal= 100;
return View()
}
}
40 | P a g e
ASP.NET MVC MR.R.N.REDDY
Example to initialize the one string Value &numericalValue with in the ViewData (controller]
& Display the Data With in the view. Finally we can Say forwarding the Datacontrol to view
page with the help of ViewData.
Step :1 Index.cshtml[design] View Data
msg
Welcome to ViewData
Welcome to viewDAta
Emp No is:111
eno
111
Step:2 HomeController.cs[code]
class HomeController
{
Public ActionResult Index()
{
ViewData[“msg”]= "welcome to ViewData";
ViewData["eno”]=111;
return View();
}
Step3: Index.csHtml[ Razor code]
41 | P a g e
ASP.NET MVC MR.R.N.REDDY
@{
Layout=null;
String str1=Viewdata[“msg”]. Tostring();
int eid=(int)ViewData[ “eno"];
}
Step:4 Index.cshtml[design Code].
<html>
<body>
<div>
<span> @Str</sapn>
Empno is: <span> @eid</span>
</div>
</body>
</html>
Example to initialize the student information i.e. sid,sname,sloc with in the controller with
the help of ViewData and forward this data to view page to display.
Step 2: HomeController.cs
Class HomeController
{
Public ActionResult Index()
{
ViewData[“sid”]=”111”;
ViewData[“sname”]=”rama”;
ViewData[“sloc”]=”hyderabad”;
Return view();
}
}
Step:3 Index.Cshtml[Razor code]
@{
Layout=null;
Int sid=(int)viewdata[“sid”];
String name=viewdata[“sname”].ToString();
String loc=viewdata[“sloc”].ToString();
}
Step :4 index.cshtml[design code]
<html>
<body>
<div>
Student id<span>@sid</span>
</br>
Student name:<sapn>@sname</span>
</br>
Student location<sapn>@sloc</span>
</div>
</body>
42 | P a g e
ASP.NET MVC MR.R.N.REDDY
</html>
Example to initialize student 3 subject marks m1,m2,m3 with the help of view data with in
the controller and calculate total marks with in the razor finally display totmarks with in the
view with in the text box.
Step:1 Index.cshtml[design] view data
M1
60
Total marks: 210
M2
70
M3
80
TempData:using tempdata we can forward the data from controller to view. Tempdata
stores the data as a pair, which contains Key - value
Key type is staring and value type is object.
43 | P a g e
ASP.NET MVC MR.R.N.REDDY
Example to forward the data from controller to view with the help of tempdata.
Step:1 Index.cshtml[Design]
Name is :Rama name
20
44 | P a g e
ASP.NET MVC MR.R.N.REDDY
<body>
<div>
Name is: <span>@data.name</span>
</br></br>
Age is: <span>@data.age </span>
</div></body></html>
Properties with view page class:-
View page is nothing but user interface.
Every viewis Representing as a user define class.
Every view page class we have an supper class i.e. Webview Page
which is part of a base class library System.web.MVC with in the view page we can access all
the following property which are defining by the micro soft with in the WebviewPage class
They are 1.Ajax
2. HTML
3. Model
4. TempData
5. URL
6.ViewBag
7. ViewContext
8.ViewData
1.Ajax:
used to set and get Ajax helper Classes
2.Html:
used to Set and get html controls helper class
3.Model:
used to Set model property of the associated view Data Dictionary object
4.TempData:
To Setand get the Tempdatawhich is required to pass to the view.
5.URL:
Used to set and get the URL for the render page
6.ViewBag :
To set or get the template required to the pass to the view
7.ViewContext:
Used to Set or get the information i.e. used to display with in the view. The information like
from tempdata or viewData.
8.ViewData:
Used ta set or get the key values pairs in the form of dictionary i.e. used to pass from
controller to view.
In previous example to pass the data from controller to view we are implementing 3
techniques 1.ViewData
2.ViewBag
3.TempData
1.ViewData
View Data Variables arestore with in the object.
To access view data Variables with in the Viewpage we can usede 3 ways Like bellow.
1. @ViewData[“keyname”]
46 | P a g e
ASP.NET MVC MR.R.N.REDDY
[email protected][“keyname”]
[email protected][“keyname”]
Lifetime of view Data Variable is only one request i.e. Current request.
After current request viewdata Variables are destroyed Automatically
Example to understand view Data Variable Life time.
Step 1 HomeController. Cs [code]
Class HomeController:
{
Public ActionResult Index()
{
ViewData[“a”]=10;
ViewData[“b”]=10.5;
ViewData[“c”]=”rama”;
return view(); }
[HttpPost]
Public ActionResult Index(String x)
{
ViewData[“x”]=”Welcome to View Data”;
return view();
}
}
Step 2: Write the below code with in the index.cshtml [view page] div session
<html>
<body>
<form id=“MyForm” method=” post”>
<p> a value is: @viewData[”a”]/p>
<p> b Vale is:@viewData[”b”]</p>
<p>c value is: @viewData[”c”]</p>
<p>x value is: @viewData[”x”]</p>
< input type="Submit" id="btnSubmit” value=”submit” />
</div>
</form>
</body>
</html>
47 | P a g e
ASP.NET MVC MR.R.N.REDDY
Observation: a,b,care the view data variable are generated the first request. But when we
click the Submit button post backrequest is generated a, b, c variables are destroyed
because view data variables life time is only up to one request.
Implement the above example to access the view data by using 2nd syntax
@ViewContext.Viewdata[“keyname”]
Implement the above example to access the view data by using 3rdsyntax
@ViewContext.Controller.Viewdata[“keyname”]
Temp Data:
Tempdata is almost all Similar to viewdata. But lifetime of Tempdata variable is one
usage i.e. once we use Tempdata variable, then it is not available for next request
or response.
A template variable will be maintained among multiple requests if it is not used
TO Create the tempdata variable, we will use the following mechanism
<syntax>
Tempdata[“keyname “]=Value
we can access the Template variable from the view in following ways
@empdata["Keyname"]
@ ViewContext.TempDate['Keyname"]
@viewcontext.Controller.TempData["Keyname"]
Example for TempData:
Step 1: Home Controller.cs
class Homecontroller.cs: conboller
{
public ActionResult Index( )
{
TampData[“a”]=10;
TempDate[“b"]=10.5;
TempData [“c”]=”rama”;
return View();
}
[Http Post]
Public ActionResult Index(string s)
{
return view();}
Step 2: write the below code within the Index.cshtml div section
<html>
<head></head>
<body> form name=”myform” method="Post”>
<div>
<p> a value is :@TempData[“a”]< /P>
<p>b value is : @TempData[“ b”] </p>
<P>c Value is : @TempData[ "c”]</p>
<input type=”submit” name=” btnSubmit” Value="submit" />
</div>
</form>
</body></html>
48 | P a g e
ASP.NET MVC MR.R.N.REDDY
when we run the above application, the output will be like below,
a value is: 10
b Valle is 10.5
C value is rama
Submit
when user click the Submit button, a,b, C values are not available and this outputwill be like
below
a value is :
b value is :
C value is :
Submit
Because, a, b, c variables are used accessed in first request immediately which are
destroyed. Due to that reason, those variables are not available for second request
(postBack request)
Example to see the value of TempData will be available for all consequence request, until
its first use.
Update the below Code within the Home Controller.cs file
[httppost]
Public ActionResult Index[string s]
{
viewData["d"]= TempData[“b"];
return view();
}
Update the belowcode whithin Index.cshtml
<html>
<body>
<form Name= "myform " method="post”>
<div>
< P>a value is :@TempData[“a”]</p>
<P>c value is :@ Temppata [“c”]</p>
<P>d value is :@viewData[“d”]</p>
<input type=”submit” name=”submit" value="submit"/>
</div>
</form>
</body>
</html>
when we run the above page,the output is like below
a value is: 10 C value
is : rama D value
is:
49 | P a g e
ASP.NET MVC MR.R.N.REDDY
Submint
Here it is not printing the d value, because d variable is not available forfirstrequest.
Observation : in this request, b Variable is not accessed which has a value called 10.5.so, it
will be available for next request.
In the above problem, within the postBack method, we assigned b value into another
variable Called d like below
Viewdata["d”]=TempData[“b”];
Due to that reason b value will be exist for second request[Postback request].
C value is:
d value is : 10.5
Submit
HTML Property: This HTML Property of a viewpage is helpful to create HTML controls
HTML helper controls are to similar HTML controls or asp.net webform Controls
Here, HTML helper Controls are capable of binding with data from the model
directory
HTML Controls are light weight controls Compared with asp.net web form control
Html helper controls do not support event handling
HTML helper Controls do not Support any view state (or) controlstate.
In Most of the cases,HTML Controls are just method which return stings
we Can create custom Html helpers by using the built io html helpers.
50 | P a g e
ASP.NET MVC MR.R.N.REDDY
Step:1 Index.cshtml
Enter Your Name :
Submit
51 | P a g e
ASP.NET MVC MR.R.N.REDDY
Male
Female
Submit
Reading
Programming
Browsing
52 | P a g e
ASP.NET MVC MR.R.N.REDDY
Example to forward the items from controller to view and within the view, bind to the dropdownlist
Step1:- Index.cshtml[Design] HomeControler
mylist
Select your country:Select Emp Id:
select .net java php
-select-
.ne 0 1 2 3
t
Object of view data
java
php select
submit .net
java
php
Step2:- Index.cshtmlviewpage code
<html>
<body>
<form id=”my form” method=”post”>
<div>
@Html.label (“lblcourse”,”select your coursename”)
@Html.DropDownList(“d1”)
<br/><br/>
<input type = “submit” id=”b+nsubmit” value=”submit”/>
</div>
</form>
</body>
</html>
Step3:-HomeController.cs code
Class HomeController
{
Public ActionResultIndex()
{
53 | P a g e
ASP.NET MVC MR.R.N.REDDY
Example to bind the dept Names to the dropdownlist and holding the deptNo’s within the viepage.
Step1:- Index.cshtml[DEsign]
-select-
HR
Techinical
Marketing
submit
54 | P a g e
ASP.NET MVC MR.R.N.REDDY
Example for html helper ListBox control by getting the values from controller to view page.
Step1:- Index.cshtml() [Design] Home.Controller
Select Your Skils: mylist
C#.net select .net java
Asp.net
0 1 2
Ado.net
Asp.Net MVC Object of view data
select
.Asp.net
Ado.net
submit Asp.net Mvc
C#.net
Asp.net
Ado.net
Asp.Net MVC
submit
55 | P a g e
ASP.NET MVC MR.R.N.REDDY
Submit
56 | P a g e
ASP.NET MVC MR.R.N.REDDY
Name = Request["txtName"];
age = Request["txtAge"].AsInt();
}
}
}
<!DOCTYPE html>
<html>
<body>
<form name="myform" method="post">
<div>
Enter ur Name: <input type="text" name="txtName" /><span>@msg</span><br /><br />
Enter ur Age: <input type="number" name="txtage"/><span>@age1</span><br /><br
/><input type="submit" name="btnsubmit" value="submit"/><br /><br />
<span>@Name </span><br /><br />
<span>@age</span>
</div>
</form>
</body>
</html>
Example for Html Helper text area controls[multi Line Text Box]
Step:1 Index.Cshtml:
Enter about YourSelf
Submit
57 | P a g e
ASP.NET MVC MR.R.N.REDDY
Submit
Submit
58 | P a g e
ASP.NET MVC MR.R.N.REDDY
{
if(Request["txtName"].IsEmpty())
{
Uname = "*plz enter user name";
}
else if(Request["txtpwd"].IsEmpty())
{
pwd = "*plz enter password";
}
else if(Request["txtpwd"].Length>=6 && Request["txtpwd"].Length <= 8)
{
pwd = "*password should be max 6 chars and min 8 chars";
}
else if(Request["txtRepwd"].IsEmpty())
{
repwd = "plz Re-enter password";
}
else if (Request["txtpwd"]==Request["txtRepwd"])
{
repwd = "* both passwords should match";
}
else
{
msg = "valid user";
}
}
}
<!DOCTYPE html>
<html>
<body>
<form id="myform" method="post">
<div>
Enter User Name: @Html.TextBox("txtName")
@Html.Label("lblName",Uname)</br><br/>
Enter password: @Html.Password("txtpwd")
@Html.Label("lblpwd",pwd) <br /><br />
Enter ReEnter Password: @Html.Password("txtRepwd")
@Html.Label("lblrepwd",repwd) <br /><br />
<input type="button" id="btnsubmit" value="submit" /><br /><br />
@Html.Label("lblmsg",msg)
</div>
</form>
</body>
</html>
59 | P a g e
ASP.NET MVC MR.R.N.REDDY
Male
Female
Submit
@{
Layout = null;
string msg = "";
if (this.IsPost)
{
if (Request["gender"].IsEmpty())
{
msg = "plz select gender";
}
else
{
msg = "your gender is: " + Request["gender"];
}
}
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<form id="myform" method="post">
<div>
@Html.RadioButton("gender", "male")Male</br></br>
@Html.RadioButton("gender", "female")Female</br></br>
<input type="submit" value="submit" id="bynsubmit" /></br></br>
@Html.Label("lblmsg", @msg)
</div>
</form>
</body>
</html>
60 | P a g e
ASP.NET MVC MR.R.N.REDDY
Reading
Programming
Browsing
61 | P a g e
ASP.NET MVC MR.R.N.REDDY
Insert
62 | P a g e
ASP.NET MVC MR.R.N.REDDY
conn.Close();
return i;
}
}
}
Implement Controller :
Open solution explorer select controller folder right click Add controller rename it as
EmpController click add button.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Adonet_insert.Models;
using System.Data;
namespace InsertEmployee.Controllers
{
public class EmpController : Controller
{
// GET: Default
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(string s)
{
if(Request["txtEno"]=="" || Request["txtEName"]==""||Request["txtEsal"]=="")
{
return View();
}
else
{
insert empobj = new insert
{
Eno = Convert.ToInt32(Request["txtEno"]),
Ename = Request["txtEname"],
Esal = Convert.ToDouble(Request["txtEsal"])
};
ViewData["i"] = empobj.InsertIntoEmp();
return View();
}
}
}
}
63 | P a g e
ASP.NET MVC MR.R.N.REDDY
64 | P a g e
ASP.NET MVC MR.R.N.REDDY
Enter EmpNo:@Html.TextBox("txtEno")
@Html.Label("lbleno",@enomsg) <br/><br />
Enter EmpName: @Html.TextBox("txtEname")
@Html.Label("lblename", @enamemsg)<br/><br />
Enter Salary: @Html.TextBox("txtEsal")
@Html.Label("lblsal", @esalmsg)<br/><br />
<input type="submit" id="btnsubmit" value="Insert" /><br/><br />
@Html.Label("lblmsg", msg)
</div>
</form>
</body>
</html>
Update the controller name
Open solution expolerer open App-start folder update the below code with in
RouteConfig.cs fill
Controller=”Emp”
Example to delete a record from Emp table on selected empNo
Step :1 Design Front End and Back End
Index.cshtml[design]
-select-
Select Emp Id: 111
*plz select empno
Delete
Record is deleted
65 | P a g e
ASP.NET MVC MR.R.N.REDDY
66 | P a g e
ASP.NET MVC MR.R.N.REDDY
return View("Index");
}
else
{
employee objdelete = new employee
{
Eno = int.Parse(Request["dropemplist"])
};
ViewData["delete"] = objdelete.DeleteEmp();
ForwordEmp();
return View("Index");
}
}
View Code:
@{
string deleteeno = "";
if (this.IsPost)
{
if (Request["dropemplist"] == "")
{
deleteeno = "* plz select Emp No...";
}
if (ViewData["delete"] != null)
{
int j = Convert.ToInt32(ViewData["delete"]);
if (j == 1)
{
deletemsg = "Record is deleted";
}
else
{
deletemsg = "Record is not deleted";
}
}
}
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<form id="myform"method="post" action="Delete">
<div>
Select Emp No: @Html.DropDownList("dropemplist", "-select-")
@Html.Label("lblenomsg",deleteeno)<br /><br/>
67 | P a g e
ASP.NET MVC MR.R.N.REDDY
Example to insert and delete a operations on Emp table by using single view
Step :1 Design Front End and Back End
Insert
Delete
Record is deleted
Model Code:
using System.Data;
namespace InsertDeleteExample1.Models
{
public class employee
{
public int Eno { get; set; }
public string Ename { get; set; }
public double Esal { get; set; }
SqlConnection conn = new
SqlConnection("server=.;uid=sa;pwd=1234;database=mydb");
68 | P a g e
ASP.NET MVC MR.R.N.REDDY
SqlCommand cmd;
public DataTable GetEmp()
{
cmd = new SqlCommand("select empid from employee",conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
public int InsertEmp()
{
cmd = new SqlCommand("insert into employee
values(@eno,@ename,@esal)",conn);
cmd.Parameters.AddWithValue("@eno",Eno);
cmd.Parameters.AddWithValue("@ename",Ename);
cmd.Parameters.AddWithValue("@esal", Esal);
conn.Open();
int i = cmd.ExecuteNonQuery();
conn.Close();
return i;
}
public int DeleteEmp()
{
cmd = new SqlCommand("delete Employee where empid=@eid",conn);
cmd.Parameters.AddWithValue("@eid", Eno);
conn.Open();
int i = cmd.ExecuteNonQuery();
conn.Close();
return i;
}
}
}
Controller Code:
using System.Data;
namespace InsertDeleteExample1.Controllers
{
public class EmpController : Controller
{
// GET: Emp
internal void ForwordEmp()
{
employee obj = new employee();
DataTable mydt = obj.GetEmp();
List<int> mylist = new List<int>();
for(int i = 0; i < mydt.Rows.Count; i++)
{
int no = (int)mydt.Rows[i]["empid"];
69 | P a g e
ASP.NET MVC MR.R.N.REDDY
mylist.Add(no);
}
ViewData["dropemplist"] = new SelectList(mylist);
}
public ActionResult Index()
{
ForwordEmp();
return View();
}
[HttpPost]
public ActionResult Insert()
{
if (Request["txteno"] == "" || Request["txtename"] == "" || Request["txtesal"] == "")
{
ForwordEmp();
return View("Index");
}
else
{
employee objInsert = new employee()
{
Eno = int.Parse(Request["txteno"]),
Ename = Request["txtename"],
Esal = double.Parse(Request["txtesal"])
};
ViewData["insert"] = objInsert.InsertEmp();
ForwordEmp();
return View("Index");
}
}
[HttpPost]
public ActionResult delete()
{
if(Request["dropemplist"]=="")
{
ForwordEmp();
return View("Index");
}
else
{
employee objdelete = new employee
{
Eno = int.Parse(Request["dropemplist"])
};
ViewData["delete"] = objdelete.DeleteEmp();
ForwordEmp();
return View("Index") } }
70 | P a g e
ASP.NET MVC MR.R.N.REDDY
View Code
@{
Layout = null;
string enomsg = "";
string enamemsg = "";
string esalmsg = "";
string deletemsg = "";
string insertmsg = "";
string deleteeno = "";
if (this.IsPost)
{
if (Request["txteno"] == "")
{
enomsg = "* plz enter Emp no...";
}
else if (Request["txtename"] == "")
{
enamemsg = "*plz enter Emp Name...";
}
else if (Request["txtesal"] == "")
{
esalmsg = "*plz enter salary";
}
else if (Request["dropemplist"] == "")
{
deleteeno = "* plz select Emp No...";
}
else
{
if (ViewData["insert"] != null)
{
int i = Convert.ToInt32(ViewData["insert"]);
if (i == 1)
{
insertmsg = "record is inserted";
}
else
{
insertmsg = "record is not inserted";
}
}
if (ViewData["delete"] != null)
{
int j = Convert.ToInt32(ViewData["delete"]);
if (j == 1)
{
deletemsg = "Record is deleted";
71 | P a g e
ASP.NET MVC MR.R.N.REDDY
}
else
{
deletemsg = "Record is not deleted";
}
}
}
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<form id="myform" method="post" action="Insert">
<div>
Enter Emp No: @Html.TextBox("txteno")
@Html.Label("lblenomsg", enomsg)<br /><br/>
Enter Emp Name: @Html.TextBox("txtename")
@Html.Label("lblenamemsg", enamemsg)<br /><br/>
Enter Salary: @Html.TextBox("txtesal")
@Html.Label("lblenomsg", esalmsg)<br /><br/>
<input type="submit" id="btnsubmit" value="Submit" /><br /><br/>
@Html.Label("lblinsertmsg", insertmsg)
</div>
</form><br /><br/>
<form id="myform2"method="post" action="Delete">
<div>
Select Emp No: @Html.DropDownList("dropemplist", "-select-")
@Html.Label("lblenomsg",deleteeno)<br /><br/>
<input type="submit" value="Delete" id="btndelete" /><br /><br/>
@Html.Label("lbldeletemsg", deletemsg)
</div>
</form>
</body>
</html>
72 | P a g e
ASP.NET MVC MR.R.N.REDDY
Eg: Example to insert and update operations on Emp table by using single view
Step :1 Design Front End and Back End
Insert
Model Code:
using System.Data;
namespace InsertDeleteExample1.Models
{
public class employee
{
public int Eno { get; set; }
public string Ename { get; set; }
public double Esal { get; set; }
SqlConnection conn = new
SqlConnection("server=.;uid=sa;pwd=1234;database=mydb");
SqlCommand cmd;
public DataTable GetEmp()
73 | P a g e
ASP.NET MVC MR.R.N.REDDY
{
cmd = new SqlCommand("select empid from employee",conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
public int InsertEmp()
{
cmd = new SqlCommand("insert into employee
values(@eno,@ename,@esal)",conn);
cmd.Parameters.AddWithValue("@eno",Eno);
cmd.Parameters.AddWithValue("@ename",Ename);
cmd.Parameters.AddWithValue("@esal", Esal);
conn.Open();
int i = cmd.ExecuteNonQuery();
conn.Close();
return i;
}
public int UpdateEmp()
{
cmd = new SqlCommand("update emp set salary=@esalwhere empid=@eid",conn);
cmd.Parameters.AddWithValue("@eid", Eno);
cmd.Parameters.AddWithValue("@esal", Esal);
conn.Open();
int i = cmd.ExecuteNonQuery();
conn.Close();
return i;
}
}
}
Controller Code:
using System.Data;
namespace InsertDeleteExample1.Controllers
{
public class EmpController : Controller
{
// GET: Emp
internal void ForwordEmp()
{
employee obj = new employee();
DataTable mydt = obj.GetEmp();
List<int> mylist = new List<int>();
for(int i = 0; i < mydt.Rows.Count; i++)
{
int no = (int)mydt.Rows[i]["empid"];
mylist.Add(no);
74 | P a g e
ASP.NET MVC MR.R.N.REDDY
}
ViewData["dropemplist"] = new SelectList(mylist);
}
public ActionResult Index()
{
ForwordEmp();
return View();
}
[HttpPost]
public ActionResult Insert()
{
if (Request["txteno"] == "" || Request["txtename"] == "" || Request["txtesal"] == "")
{
ForwordEmp();
return View("Index");
}
else
{
employee objInsert = new employee()
{
Eno = int.Parse(Request["txteno"]),
Ename = Request["txtename"],
Esal = double.Parse(Request["txtesal"])
};
ViewData["insert"] = objInsert.InsertEmp();
ForwordEmp();
return View("Index");
}
}
[HttpPost]
public ActionResult update()
{
if(Request["dropemplist"]=="" || Request[“txtNewSal”]=””)
{
ForwordEmp();
return View("Index");
}
else
{
employee objupdate = new employee
{
Eno = int.Parse(Request["dropemplist"]),
Esal=double.parse(Request[“txtnewsal”])
};
ViewData["update"] = objupdate.UpdateEmp();
ForwordEmp();
return View("Index")
75 | P a g e
ASP.NET MVC MR.R.N.REDDY
}
}
View Code
@{
Layout = null;
string enomsg = "";
string enamemsg = "";
string esalmsg = "";
string enoupdatemsg = "";
string insertmsg = "";
string updatemsg = "";
if (this.IsPost)
{
if (Request["txteno"] == "")
{
enomsg = "* plz enter Emp no...";
}
else if (Request["txtename"] == "")
{
enamemsg = "*plz enter Emp Name...";
}
else if (Request["txtesal"] == "")
{
esalmsg = "*plz enter salary";
}
else if (Request["updateemplist"] == "")
{
enoupdatemsg= "* plz select Emp No...";
}
else
{
if (ViewData["insert"] != null)
{
int i = Convert.ToInt32(ViewData["insert"]);
if (i == 1)
{
insertmsg = "record is inserted";
}
else
{
insertmsg = "record is not inserted";
}
}
if (ViewData["updatete"] != null)
{
int j = Convert.ToInt32(ViewData["update"]);
if (j == 1)
76 | P a g e
ASP.NET MVC MR.R.N.REDDY
{
updatemsg = "Record is updated";
}
else
{
updatemsg = "Record is not updated";
}
}
}
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<form id="myform" method="post" action="Insert">
<div>
Enter Emp No: @Html.TextBox("txteno")
@Html.Label("lblenomsg", enomsg)<br /><br/>
Enter Emp Name: @Html.TextBox("txtename")
@Html.Label("lblenamemsg", enamemsg)<br /><br/>
Enter Salary: @Html.TextBox("txtesal")
@Html.Label("lblenomsg", esalmsg)<br /><br/>
<input type="submit" id="btnsubmit" value="Submit" /><br /><br/>
@Html.Label("lblinsertmsg", insertmsg)
</div>
</form><br /><br/>
<form id="myform2"method="post" action="Update">
<div>
Select Emp No: @Html.DropDownList("dropemplist", "-select-")
@Html.Label("lblenomsg",updateeno)<br /><br/>
<input type="submit" value="Update" id="btnupdate" /><br /><br/>
@Html.Label("lblupdatemsg", updatemsg)<br /><br/>
</div>
</form>
</body>
</html>
77 | P a g e
ASP.NET MVC MR.R.N.REDDY
Eg: Example to display emp table with in html table by using Asp.netmvc
Step 1: Design of Index.cs
Model code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
namespace MVCHtmlTableExample1.Models
{
public class Employee
{
SqlConnection conn = new
SqlConnection("server=.;database=mydbMvc;uid=sa;pwd=1234");
SqlCommand cmd;
public DataTable GetEmp()
{
cmd = new SqlCommand("select * from emp", conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
}
}
Controller code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCHtmlTableExample1.Models;
using System.Data;
namespace MVCHtmlTableExample1.Controllers
{
78 | P a g e
ASP.NET MVC MR.R.N.REDDY
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<form>
<div>
<table border="1">
<tr>
<th>Employee No</th>
<th>Employee Name</th>
<th>Employee Salary</th>
</tr>
@{
foreach(System.Data.DataRow myrow in ViewBag.emp.Rows)
{
<tr>
<td>@myrow["empno"]
</td>
<td>@myrow["empname"]</td>
<td>@myrow["salary"]</td>
</tr>
}
}
</table>
79 | P a g e
ASP.NET MVC MR.R.N.REDDY
</div>
</form>
</body>
</html>
Eg: Example to delete record on emp table by using Html Table
Step 1: Index.cshtml[Design]
Record is Deleted
80 | P a g e
ASP.NET MVC MR.R.N.REDDY
81 | P a g e
ASP.NET MVC MR.R.N.REDDY
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<form name="myform" method="post">
<div>
<table border="1">
<tr>
<th>Employee No</th>
<th>Employee Name</th>
<th>Employee Salary</th>
</tr>
@{
foreach(System.Data.DataRow myrow in ViewBag.Emp.Rows)
{
<tr>
<td>@myrow["empno"]</td>
<td>@myrow["empname"]</td>
<td>@myrow["salary"]</td>
<td>
@Html.ActionLink("Delete", "Delete",new { }
)
</td>
</tr>
}
}
</table>
</div>
</form>
</body>
</html>
Eg: Example to update the Employee Salary by Using Html table UpdatingIndex.cshtml
Edit
EmployeeNO EmployeeName Employeesalary 333
EmoNo :
Salary is updated
82 | P a g e
ASP.NET MVC MR.R.N.REDDY
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data;
namespace MvcEditEmpinAdo.Models
{
public class Employee
{
SqlConnection conn = new
SqlConnection("server=.;uid=sa;pwd=1234;database=mydbmvc");
SqlCommand cmd;
public int Eno { get; set; }
public string Ename { get; set; }
public double Esal { get; set; }
public DataTable GetEmp()
{
cmd = new SqlCommand("select * from Emp", conn);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
return dt;
}
public DataTable GetCurrentEmpDetails()
{
cmd = new SqlCommand("select empno,salary from Emp where empno=@eno",
conn);
cmd.Parameters.AddWithValue("@eno",Eno);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
public double updateSal()
{
cmd = new SqlCommand("update emp set salary=@sal where empno=@eno
",conn);
cmd.Parameters.AddWithValue("@sal", Esal);
cmd.Parameters.AddWithValue("@eno", Eno);
conn.Open();
int i = cmd.ExecuteNonQuery();
conn.Close();
return i;
}
}
83 | P a g e
ASP.NET MVC MR.R.N.REDDY
Controller Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using MvcEditEmpinAdo.Models;
namespace MvcEditEmpinAdo.Controllers
{
public class DefaultController : Controller
{
internal void Forwordemp()
{
Employee objemp = new Employee();
ViewBag.emp = objemp.GetEmp();
}
// GET: Default
public ActionResult Index()
{
Forwordemp();
return View();
}
public ActionResult EditIndex()
{
Employee ObjEmp = new Employee
{
Eno = int.Parse(Request.QueryString["eno"])
};
ViewBag.emp = ObjEmp.GetCurrentEmpDetails();
return View("UpdateIndex");
}
public ActionResult UpdateIndex()
{
Employee objemp = new Employee
{
Eno=int.Parse(Request["txtEno"]),
Esal=double.Parse(Request["txtEsal"])
};
ViewBag.update = objemp.updateSal();
Forwordemp();
return View();
}
}
}
Note : Here we add two views
View 1: right click on Index Action Method Add View click Add button with this
Index.Cshtml will Add,
View 2: right click on UpdateIndex Action Method Add View click Add button with
this UpdateIndex.Cshtml will Add
View Code: Index.Cshtml
@{
Layout = null;
}
<!DOCTYPE html>
<html>
84 | P a g e
ASP.NET MVC MR.R.N.REDDY
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<form name="myform" method="post">
<div>
<table border="1">
<tr>
<th>Employee No</th>
<th>employee Name</th>
<th>Salary</th>
<th>Edit</th>
</tr>
@{
foreach (System.Data.DataRow myrow in ViewBag.emp.Rows)
{
<tr>
<td>@myrow["empno"]</td>
<td>@myrow["empname"]</td>
<td>@myrow["salary"]</td>
<td>@Html.ActionLink("Edit","EditIndex",new { eno=myrow["empno"]})
</td>
</tr>
}
}
</table>
</div>
</form>
</body>
</html>
UpdateIndex.cshtml [ Code]
@using System.Data;
@{
Layout = null;
string eno = "";
string esal = "";
string esalmsg = "";
string msg = "";
foreach (DataRow myrow in ViewBag.emp.Rows)
{
eno = myrow["empno"].ToString();
esal = myrow["salary"].ToString();
}
if (this.IsPost)
{
if (Request["txtEsal"].IsEmpty())
{
esalmsg = "plz Enter Emp Salary";
}
else
{
int i =ViewBag.update;
if (i == 1)
{
msg = "Salary is Updated";
}
else
85 | P a g e
ASP.NET MVC MR.R.N.REDDY
{
msg = "Salary is Not Updated";
}
}
}
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>UpdateIndex</title>
</head>
<body>
<form id="myform" method="post" action="~/Default/UpdateIndex">
<div>
Employee No : <input type="text" value="@eno" id="txtEno" readonly />
<br /><br />
Enter New Employee Salary : <input type="text" id="txtEsal"
value="@esal"/>
@Html.Label("lblmsg",esalmsg)
<br /><br />
<input type="submit" name="btnupdate" value="Update" />
<input type="submit" name="btnGoBack" value="GoBack"
formaction="~/Default/Index" />
<br /><br />
@Html.Label("lblUpdate",msg)
</div>
</form>
</body>
</html>
Example to Insert a record into Emp Table:
Step:1 Design of front end and back end
Enter Emp ID :
Enter Salary :
insert
Model Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
namespace INSERTARECORDBYUSINGHTMLTABLE.Models
86 | P a g e
ASP.NET MVC MR.R.N.REDDY
{
public class Employee
{
public int Eno{get;set; }
public string Ename{get; set; }
public double Esal{get; set; }
SqlConnection conn = new
SqlConnection("server=.;database=mydbmvc;uid=sa;pwd=1234");
SqlCommand cmd;
public int insertemp()
{
cmd = new SqlCommand("insert into emp
values(@eno,@ename,@esal)",conn);
cmd.Parameters.AddWithValue("@eno", Eno);
cmd.Parameters.AddWithValue("@ename", Ename);
cmd.Parameters.AddWithValue("@esal", Esal);
conn.Open();
int i = cmd.ExecuteNonQuery();
conn.Close();
return i;
}
}
}
Controller Code :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using INSERTARECORDBYUSINGHTMLTABLE.Models;
namespace INSERTARECORDBYUSINGHTMLTABLE.Controllers
{
public class EmpController : Controller
{
// GET: Emp
public ActionResult Index()
{
return View();
}
public ActionResult Insert()
{
if (Request["txtempno"] == "" || Request["txtempname"] == ""
|| Request["txtempsal"] == "")
{
return View("Index");
}
else
{
Employee obj = new Employee
{
87 | P a g e
ASP.NET MVC MR.R.N.REDDY
Eno = int.Parse(Request["txtempno"]),
Ename = Request["txtempname"],
Esal = double.Parse(Request["txtempsal"])
};
ViewBag.insert = obj.insertemp();
return View("Index");
}
}
}
}
View Code:
@using System.Data;
@{
Layout = null;
string enomsg = "";
string enamemsg = "";
string esalmsg = "";
string insertmsg = "";
if (this.IsPost)
{
if (Request["txtempno"].IsEmpty())
{
enomsg = "pls enter empno";
}
else if (Request["txtempname"].IsEmpty())
{
enamemsg = "pls enter empname";
}
else if (Request["txtempsal"].IsEmpty())
{
esalmsg = "pls enter new salary";
}
else
{
if (ViewBag.insert != null)
{
int j = ViewBag.insert;
if (j == 1)
{
insertmsg = "record is inserted";
}
else
{
insertmsg = "record is not insertred";
}
}
}
}
}
<!DOCTYPE html>
88 | P a g e
ASP.NET MVC MR.R.N.REDDY
<html>
<head>
<meta name="viewport" content="width=device-width" />
</head>
<body>
<form id="myform" method="post">
<div>
Enter Emp ID : @Html.TextBox("txtempno")@Html.Label("lbleno", enomsg)
<br /><br />
Enter Emp Name :
@Html.TextBox("txtempname")@Html.Label("lblename",enamemsg)
<br /><br />
Enter Salary : @Html.TextBox("txtempsal")@Html.Label("lblesal", esalmsg)
<br /><br /><input type="submit" value="insert" name="btninsert"
formaction="Insert" />
<br /><br />
@Html.Label("lblmsg", insertmsg)
</div>
</form>
</body>
</html>
Example to Curd Operations (Inser,Delete,Update) by using Html Table:
Step:1 Design of Front End And Back End
Employee no Employee name Employee salary DELETE EDIT EmpNo EmpName Salary
insert
model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
namespace CurdOperationsONHTMLTable.Models
{
public class Employee
{
public int Eno{get; set;}
public string Ename{get;set; }
public double Esal{get;set; }
89 | P a g e
ASP.NET MVC MR.R.N.REDDY
90 | P a g e
ASP.NET MVC MR.R.N.REDDY
controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using CurdOperationsONHTMLTable.Models;
namespace CurdOperationsONHTMLTable.Controllers
{
public class EmpController : Controller
{
internal void forwardemp()
{
Employee obj = new Employee();
ViewBag.emp = obj.GetEmp();
}
// GET: Emp
public ActionResult Index()
{
forwardemp();
return View();
}
public ActionResult DeleteCntrlEmp()
{
Employee obj = new Employee
{
Eno = int.Parse(Request.QueryString["eno"])
};
ViewBag.delete = obj.DeleteEmp();
forwardemp();
return View("Index");
}
public ActionResult EditEmp()
{
Employee obj = new Employee
{
Eno = int.Parse(Request.QueryString["eno"])
};
ViewBag.emp = obj.GetEmpDetails();
forwardemp();
return View("EditIndex");
}
public ActionResult EditIndex()
{
if (Request["txtnewsal"] == "")
{
return View();
}
else
91 | P a g e
ASP.NET MVC MR.R.N.REDDY
{
Employee obj = new Employee
{
Eno = int.Parse(Request["txteno"]),
Esal = double.Parse(Request["txtnewsal"])
};
ViewBag.update = obj.UpdateEmp();
forwardemp();
return View();
}
}
public ActionResult Insert()
{
if(Request["txtempno"]==""||Request["txtempname"]==""||Request["txtempsal"]=="")
{
forwardemp();
return View("Index");
}
else
{
Employee obj = new Employee
{
Eno = int.Parse(Request["txtempno"]),
Ename = Request["txtempname"],
Esal =double.Parse( Request["txtempsal"])
};
ViewBag.insert = obj.InsertEmp();
forwardemp();
return View("Index");
}
}
}
}
VIEW1
@using System.Data;
@{
Layout = null;
string enomsg = "";
string enamemsg = "";
string esalmsg = "";
string insertmsg = "";
if(this.IsPost)
{
if(Request["txtempno"].IsEmpty())
{
enomsg = "pls enter empno";
}
else if(Request["txtempname"].IsEmpty())
{
92 | P a g e
ASP.NET MVC MR.R.N.REDDY
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<form id="myform" method="post">
<div>
<table border="1">
<tr>
<th>Employee no</th>
<th>Employee name</th>
<th>Employee salary</th>
<th>DELETE</th>
<th>EDIT</th>
</tr>
@{
foreach(DataRow myrow in ViewBag.emp.Rows)
{
<tr>
<td>@myrow[0]</td>
<td>@myrow[1]</td>
<td>@myrow[2]</td>
<td>@Html.ActionLink("delete","DeleteCntrlEmp",new {eno=myrow["empno"]})</td>
<td>@Html.ActionLink("edit", "EditEmp", new {eno=myrow["empno"]})</td>
93 | P a g e
ASP.NET MVC MR.R.N.REDDY
</tr>
}
}
<tr>
<td>
@Html.TextBox("txtempno")
</td>
<td>@Html.TextBox("txtempname")</td>
<td>@Html.TextBox("txtempsal")</td>
<td><input type="submit" value="insert" name="btninsert" formaction="Insert" /></td>
</tr>
<tr>
<td>@Html.Label("lbleno",enomsg)
</td>
<td>@Html.Label("lblename",enamemsg)</td>
<td>@Html.Label("lblesal",esalmsg)</td>
</tr>
</table>
@Html.Label("lblmsg",insertmsg)
</div>
</form>
</body>
</html>
VIEW 2: EditIndex:
@using System.Data;
@{
Layout = null;
string enomsg = "";
string esalmsg = "";
string newsalmsg = "";
string msg = "";
foreach(DataRow myrow in ViewBag.emp.Rows)
{
enomsg = myrow["empno"].ToString();
esalmsg = myrow["salary"].ToString();
}
if(this.IsPost)
{
if(Request["txtesal"]=="")
{
newsalmsg = "pls enter new salary";
}
else
{
int i = ViewBag.update;
if(i==1)
{
msg = "salary is updated";
}
94 | P a g e
ASP.NET MVC MR.R.N.REDDY
else
{
msg = "salary is not updated";
}
}
}
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>editindex</title>
</head>
<body>
<form id="myform" method="post" action="~/Emp/EditIndex">
<div>
empno is:<input type="text" value="@enomsg" name="txteno" readonly /><br /><br />
enter new salary:<input type="text" value="@esalmsg" name="txtnewsal" />
@Html.Label("lblmsg",newsalmsg)
<br /><br />
<input type="submit" value="update" name="btnupdate" />
<input type="submit" value="GoBack" name="btngoback" formaction="~/Emp/Index" />
<br /><br />
@Html.Label("lblmsg",msg)
</div>
</form>
</body>
</html>
95 | P a g e
ASP.NET MVC MR.R.N.REDDY
Linq
What is linq?
Linq stands for Language Integrated Query , Which was introduced by the Micro Soft,with
>net Framework 3.5
Linq is advanced data access object in .net,Ado.Net is traditional data access object in .Net
What we can do by using Linq?
Using Ado.Net a .Net application can communicate the databases , similarly using also a .Net
application can communicate the database.
What is the difference between Ado.Net and linq?
Using Ado.Net to communicate the data bases with in the .Net application we will write the
Sql Commands like select,Insert,Update,Delete,Create &...
But using linq to communicate the databases with in the .Net application we don’t required
to write SqlCommands these Sqlcommands we can implement by using any one of the .Net
language like C#.Net or Vb.Net Like below.
Sql
Database
.Net Application LInQ
C#
Database
Note : Linq is providing predefined method for insert,update,delete&...
But retrieving data from database linq is provided one Query it is called as linq query.
Syntax for linq Query :
Var v1=from <variableName>in<datasourse>[clauses]select<varibleName>;
What is OR tool:
To communicate the data Sources by using linq Microsoft is providing one predefing tool
called OR tool( object relational)
What will provided by OR tool?
OR tool will be providing one predefined class that predefining class will having various
predefined methods to implement remaining operations on databases like
insert,update,delete and so on...
96 | P a g e
ASP.NET MVC MR.R.N.REDDY
Example to retrieve the data from list collections by using Linq which are garter than 20
class Program
{ OutPut
static void Main(string[] args)
{ 30
List<int> emplist = new List<int> { 30, 20, 50, 40, 10 };
50
var v1 = from eno in emplist where eno>20 select eno;
foreach(int i in v1) 40
{
Console.WriteLine(i);
}
Console.ReadLine();
}
Example to retrieve the data from list collections by using Linq which are garter than 20 in
Order
class Program
{ OutPut
static void Main(string[] args)
{ 30
List<int> emplist = new List<int> { 30, 20, 50, 40, 10 };
40
var v1 = from eno in emplist where eno>20 OrderBy select eno;
50
foreach(int i in v1)
{
Console.WriteLine(i);
}
Console.ReadLine();
}
97 | P a g e
ASP.NET MVC MR.R.N.REDDY
LINQ To SQL:
Example to display emp table by using Linq In Asp.Net
Step:1 Design front end and back End:
WebForm1.aspx[Design] DataBase
EmployeeN EmployeeName EmployeeSalary Empno EmpName Salary
o 111 Rama 1000
111 Rama 1000 222 Sitha 2000
222 Sitha 2000
333 Ravi 3000
333 Ravi 3000
Dispaly
98 | P a g e
ASP.NET MVC MR.R.N.REDDY
Insert
99 | P a g e
ASP.NET MVC MR.R.N.REDDY
100 | P a g e
ASP.NET MVC MR.R.N.REDDY
Update
101 | P a g e
ASP.NET MVC MR.R.N.REDDY
</table>
</div>
</form>
</body>
</html>
Update the Routeconfig.cs file
Controller=”Emp” action=”Display”
102 | P a g e
ASP.NET MVC MR.R.N.REDDY
Insert
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MvcLinqInsertEmployeeExample.Models
{
public class Employee
{
public int Eid { get; set; }
public string Ename { get; set; }
public double Esal { get; set; }
objEmp.eid = Eid;
objEmp.ename = Ename;
objEmp.esal=Esal;
try
{
linqobj.Emps.InsertOnSubmit(objEmp);
linqobj.SubmitChanges();
return 1;
}
catch
{
return 0;
}
}
}
}
Controller code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
103 | P a g e
ASP.NET MVC MR.R.N.REDDY
using MvcLinqInsertEmployeeExample.Models;
namespace MvcLinqInsertEmployeeExample.Controllers
{
public class EmpController : Controller
{
// GET: Stu
public ActionResult Insert()
{
return View();
}
[HttpPost]
public ActionResult Insert(string s)
{
};
ViewBag.i = objstu.insertintoEmp();
return View();
}
}
}
}
View Code:
@{
Layout = null;
string eidmsg = "";
string enamemsg = "";
string esalmsg=””;
string msg = "";
if (IsPost)
{
if (Request["txtEid"] == "")
{
eidmsg = "*plz enter Emp ID";
}
else if(Request["txtEName"]=="")
{
enamemsg = "*plz enter Emp Name";
}
else if(Request["txtEsal"]=="")
{
esalmsg = "*plz enter Emp salary";
}
104 | P a g e
ASP.NET MVC MR.R.N.REDDY
else
{
int j = (int)ViewBag.i;
if(j==1)
{
msg = "Record is Inserted ";
}
else
{
msg = "Record is Not Inserted";
}
}
}
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Insert</title>
</head>
<body>
<form id="Myform" method="post">
<div>
Enter Employee ID: @Html.TextBox("txtEid")
@Html.Label("lblEid",eidmsg)
<br /><br />
ENter Employee Name @Html.TextBox("txtEname")
@Html.Label("lblEname",enamemsg)
<br /><br />
ENter Employee salary @Html.TextBox("txtEsal")
@Html.Label("lblESal",esalmsg)
<br/><br/>
<input type="submit" id="btnInsert" value="Insert" />
<br /><br />
@Html.Label("lblmsg",msg)
</div>
</form>
</body>
</html>
Delete
105 | P a g e
ASP.NET MVC MR.R.N.REDDY
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MvcLinqDeleteEmployeeExample.Models
{
public class Employee
{
}
}
Controller code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcLinqDeleteEmployeeExample.Models;
namespace MvcLinqDeleteEmployeeExample.Controllers
{
public class EmpController : Controller
{
internal void Emp()
{
Employee objemp = new Employee();
ViewData["d1"] = new SelectList(objemp.GetEmpid());
}
// GET: Emp
public ActionResult Delete()
{
Emp();
return View();
}
[HttpPost]
public ActionResult Delete(string s)
{
Emp();
if (Request["d1"] == "")
{
return View();
}
else
106 | P a g e
ASP.NET MVC MR.R.N.REDDY
{
Employee obj = new Employee()
{
Eid = int.Parse(Request["d1"])
};
ViewData["d"] = obj.DeleteEmp();
return View();
}
}
}
}
View code:
@{
Layout = null;
string eidmsg = "";
string msg = "";
if (IsPost)
{
if (Request["d1"] == "")
{
eidmsg = "*plz select Valid Emp id";
}
else
{
int j = (int)ViewData["d"];
if (j == 1)
{
msg = "record is Deleted";
}
else
{
msg = "record is not Delted";
}
}
}
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Delete</title>
</head>
<body>
<form id="myfrom" method="post">
<div>
Select Emp Id: @Html.DropDownList("d1","-select-")
@Html.Label("lbleid", eidmsg)
<br/><br />
<input type="submit" id="btnDelete" value="Delete" />
@Html.Label("lblmsg",msg)
</div>
</form>
</body>
</html>
107 | P a g e
ASP.NET MVC MR.R.N.REDDY
Update
record is Updated
ModelCode:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MvcLinqUpdateEmployeeExample.Models
{
public class Employe
{
LinqToSqlDataContext obj = new LinqToSqlDataContext();
public int Eid { get; set; }
public double Esal { get; set; }
public int UpdateEmp()
{
employee objemp = obj.employees.Single(emp => emp.empid == Eid);
objemp.salary =(decimal)Esal;
obj.SubmitChanges();
return 1;
}
}
}
Controller Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcLinqUpdateEmployeeExample.Models;
namespace MvcLinqUpdateEmployeeExample.Controllers
{
public class EmpController : Controller
{
// GET: Emp
public ActionResult Update()
{
return View();
}
[HttpPost]
public ActionResult Update(string s)
{
if (Request["txtEid"] == "" || Request["txtNewSal"] == "")
{
return View();
}
108 | P a g e
ASP.NET MVC MR.R.N.REDDY
else
{
Employe objemp = new Employe
{
Eid = int.Parse(Request["txtEid"]),
Esal = double.Parse(Request["txtNewSal"])
};
ViewBag.v = objemp.UpdateEmp();
return View();
}
}
}
}
View Code:
@{
Layout = null;
string eidmsg = "";
string esalmsg = "";
string msg = "";
if (IsPost)
{
if(Request["txtEid"]=="")
{
eidmsg = "* plz enter Empid";
}
else if(Request["txtNewSal"]=="")
{
esalmsg = "* plz enter New salary";
}
else
{
int j = ViewBag.v;
if(j==1)
{
msg = "record is Updated";
}
else
{
msg = "record is not Updated";
}
}
}
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Update</title>
</head>
<body>
<form id="myform" method="post">
<div>
Enter Emp ID: @Html.TextBox("txtEid")
@Html.Label("lblEid", eidmsg)
<br /><br />
Enter New Salary:@Html.TextBox("txtNewSal")
@Html.Label("lblEsal", esalmsg)
<br />
<br />
<input type="submit" id="btnUpdate" value="Update" />
109 | P a g e
ASP.NET MVC MR.R.N.REDDY
Add
Model Code:-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MvcLinqCurdExample1.Models
{
public class Employee
{
linqtosqlDataContext objlink = new linqtosqlDataContext();
public int Eno { get; set; }
public string Ename{get; set; }
public decimal Esal{get; set; }
public IQueryable Display()
{
var v1 = from empnew in objlink.emps select empnew;
return v1;
}
public IQueryable GetDetails()
{
var v1 = from empnew in objlink.emps where empnew.empno==Eno select empnew;
return v1;
}
public int Insert()
{
emp objemp = new emp();
objemp.empno = Eno;
objemp.empname = Ename;
110 | P a g e
ASP.NET MVC MR.R.N.REDDY
objemp.salary = Esal;
try
{
objlink.emps.InsertOnSubmit(objemp);
objlink.SubmitChanges();
return 1;
}
catch
{
return 0;
}
}
public int Delete()
{
emp objemp = objlink.emps.Single(empnew => empnew.empno == Eno);
try
{
objlink.emps.DeleteOnSubmit(objemp);
objlink.SubmitChanges();
return 1;
}
catch
{
return 0;
}
}
public int Update()
{
emp objemp = objlink.emps.Single(empnew => empnew.empno == Eno);
objemp.salary = Esal;
try
{
objlink.SubmitChanges();
return 1;
}
catch
{
return 0;
}
}
}
}
controller code:-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcLinqCurdExample1.Models;
namespace MvcLinqCurdExample1.Controllers
{
public class EmpController : Controller
{
// GET: Emp
internal void Display()
{
Employee obj = new Employee();
ViewBag.emp = obj.Display();
}
111 | P a g e
ASP.NET MVC MR.R.N.REDDY
// GET: Home
public ActionResult Index()
{
Display();
return View();
}
[HttpPost]
public ActionResult Insertemp()
{
Display();
if (Request["txteno"] == "")
{
ViewBag.eno = "Pls enter eno";
}
int i = obj.Update();
112 | P a g e
ASP.NET MVC MR.R.N.REDDY
if (i == 1)
{
ViewBag.msg = "salary is updated";
}
else
{
ViewBag.msg = "salary is not updated";
}
return View("UpdateIndex");
}
public ActionResult Delete()
{
Display();
Employee obj = new Employee
{
Eno = int.Parse(Request.QueryString["eno"])
};
int i = obj.Delete();
if (i == 1)
{
ViewBag.msg = "record is deleted";
}
else
{
ViewBag.msg = "record is not deleted";
}
return View("Index");
}
}
}
Index.cshtml code:-
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<form id="myform" method="post">
<div>
<table border="1">
<tr>
<th>EmpNo</th>
<th>EmpName</th>
<th>EmpSalary</th>
</tr>
@foreach (var item in ViewBag.emp)
{
<tr>
<td>@item.empno</td>
<td>@item.empname</td>
<td>@item.salary</td>
<td>
@Html.ActionLink("Edit", "EditIndex", new { eno = item.empno })</td>
<td>
@Html.ActionLink("delete", "Delete", new { eno = item.empano })</td>
</tr>
113 | P a g e
ASP.NET MVC MR.R.N.REDDY
}
<tr>
<td>@Html.TextBox("txteno")</td>
<td>@Html.TextBox("txtename")</td>
<td>@Html.TextBox("txtesal")</td>
<td><input type="submit" id="btnadd" value="Add" formaction="Insertemp" /></td>
</tr>
<tr>
<td><span>@ViewBag.eno</span></td>
<td><span>@ViewBag.ename</span></td>
<td><span>@ViewBag.esal</span></td>
</tr>
</table>
<span>@ViewBag.msg</span>
</div>
</form>
</body>
</html>
UpdateIndex.cshtml:-
@{
Layout = null;
int eno = 0;
decimal esal = 0;
if (ViewBag.n != null)
{
foreach (var item in ViewBag.n)
{
eno = item.eno;
esal = item.salry;
}
}
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>UpdateIndex</title>
</head>
<body>
<form id="myform" method="post" action="~/Emp/UpdateIndex">
<div>
Enter empNo:<input type="text" value="@eno" name="txtempno" readonly/><br/>
Enter new salary:<input type="text" value="@esal" name="txtsal" />
<input type="submit" id="btn" value="Update" /><br />
<input type="submit" id="btngo" value="GoBack" formaction="~/Emp/Index" />
<span>@ViewBag.msg</span>
</div>
</form>
</body>
</html>
Entity FrameWork
Wat is Entity Framework?
Entity frame work is a .Net Advanced data access technology , it always .Net Application to
Communicate to database.
114 | P a g e
ASP.NET MVC MR.R.N.REDDY
Database
.Net application Linq
Database
.Net application Entity FrameWork
115 | P a g e
ASP.NET MVC MR.R.N.REDDY
Webform1.aspx[Design] Mydatabase
}
}
}
Enter Emp NO :
Enter EMp Name :
116 | P a g e
Enter Salary :
Insert
ASP.NET MVC MR.R.N.REDDY
117 | P a g e
ASP.NET MVC MR.R.N.REDDY
{
public class EmpController : Controller
{// GET: Emp
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Insert()
{
Employee objmodel = new Employee
{
Eno = int.Parse(Request["txtEno"]),
Ename = Request["txtEname"],
Esal = decimal.Parse(Request["txtEsal"])
};
ViewData["Insert"] = objmodel.InsertIntoEmp();
return View("Index");
}
}
}
Step:6 Adding View: [Index.cshtml]
@{
Layout = null;
string msg = "";
if (this.IsPost)
{
int i = (int)ViewData["Insert"];
if (i == 1)
{
msg = "Record is Inserted";
}
else
{
msg = "Record IS Not Inserted";
}
}
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<form id="myform" method="post">
<div>
Enter Emp NO : @Html.TextBox("txtEno")
<br /><br />
Enter EMp Name : @Html.TextBox("txtEname")
<br /><br />
Enter Salary : @Html.TextBox("txtEsal")
<br /><br />
118 | P a g e
ASP.NET MVC MR.R.N.REDDY
Enter Emp NO :
Delete
119 | P a g e
ASP.NET MVC MR.R.N.REDDY
namespace MvcAspEmpDeleteExample.Controllers
{
public class EmpController : Controller
{
// GET: Emp
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Delete()
{
Employee objModel = new Employee
{
Eno = int.Parse(Request["txtEno"])
};
ViewData["Delete"] = objModel.DeleteEno();
return View("Index");
}
}
}
View Code :
@{
Layout = null;
string msg = "";
if(this.IsPost)
{
int i = (int)ViewData["Delete"];
if (i == 1)
{
msg = "Record is Delete";
}
else
{
msg = "record is not Deleted";
}
}
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<form id="myform" method="post">
<div>
Enter Emp NO : @Html.TextBox("txtEno")
<br /><br />
<input type="submit" name="btnDelete" value="Delete" formaction="~/Emp/Delete" />
<br /><br />
@Html.Label("lblmsg",msg)
</div>
</form>
</body>
</html>
Example to Update the employee Salary:
Step :1 Design front end and back end
namespace MvcEfEmpUpdateExample.Controllers
{
public class EmpController : Controller
{
// GET: Emp
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Update()
121 | P a g e
ASP.NET MVC MR.R.N.REDDY
{
Employee objmodel = new Employee
{
Eno = int.Parse(Request["txtEno"]),
Esal = decimal.Parse(Request["txtEsal"])
};
ViewData["UpdateEval"] = objmodel.UpdateEmp();
return View("Index");
}
}
}
Step:6 View Code:[Index.cshtml]
@{
Layout = null;
string msg = "";
if (this.IsPost)
{
int i = (int)ViewData["UpdateEval"];
if (i == 1)
{
msg = "salary is Updated";
}
else
{
msg = "salary is not Updated";
}
}
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<form id="myform" method="post">
<div>
Enter Emp No : @Html.TextBox("txtEno")
<br /><br />
Enter Emp Name : @Html.TextBox("txtEsal")
<br /><br />
<input type="submit" id="txtUpdated" value="Update" formaction="~/Emp/Update" />
<br /><br />
@Html.Label("lblmsg",msg)
</div>
</form>
</body>
</html>
Update RouteConfig.cs Controller=”Emp”.
Example to Delete a record from Emp table by using drop down list
Step1:Design of front end and back end
-Select-
select EmpNo :
122 | P a g e
Delete
ASP.NET MVC MR.R.N.REDDY
123 | P a g e
ASP.NET MVC MR.R.N.REDDY
{
Employee objemp = new Employee();
ViewData["dropEmpNoList"] = new SelectList(objemp.GetEno());
}
// GET: Emp
public ActionResult Index()
{
ForwordEmpNo();
return View();
}
[HttpPost]
public ActionResult Delete()
{
Employee objemp = new Employee
{
Eno = int.Parse(Request["dropEmpNoList"])
};
ViewData["delvalue"] = objemp.DeleteEmp();
ForwordEmpNo();
return View("Index");
}
}
}
View Code:
@{
Layout = null;
string msg = "";
if (this.IsPost)
{
int i = (int)ViewData["delvalue"];
if (i == 1)
{
msg = "Record is Deleted";
}
else
{
msg = "Record is not Deleted";
}
}
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<form id="myform" method="post">
<div>
select EmpNo : @Html.DropDownList("dropEmpNoList","-Select-")
<br /><br />
<input type="submit" id="btnDelete" value="Delete"formaction="~/Emp/Delete" />
<br /><br />
@Html.Label("lblmsg",msg)
</div>
</form>
</body>
</html>
Example to Deleting Record using Two Drop Downs & Entity Framework
124 | P a g e
ASP.NET MVC MR.R.N.REDDY
Delete
Record is Deleted
return dnos;
return enos;
125 | P a g e
ASP.NET MVC MR.R.N.REDDY
try
objcomp.emps.Remove(objemp);
objcomp.SaveChanges();
return 1;
catch
return 0;
{
//
// GET: /Emp/
public void ForwardDeptno()
{
Employee obj = new Employee();
ViewBag.dnos = obj.GetDnos();
}
ForwardDeptno();
return View();
126 | P a g e
ASP.NET MVC MR.R.N.REDDY
[HttpPost]
dno = int.Parse(Request["DropDnosList"])
};
ViewBag.enos=obj.GetEnos();
ForwardDeptno();
return View("Index");
[HttpPost]
eno = int.Parse(Request["DropEnosList"])
};
ViewData["delvalue"] = obj.DeleteEmp();
ForwardDeptno();
ViewBag.enos = obj.GetEnos();
return View("Index");
}
}
@{
Layout = null;
string msg = "";
if(this.IsPost)
127 | P a g e
ASP.NET MVC MR.R.N.REDDY
{
if(Request["btnDelete"]=="Delete")
{
int i = (int)ViewData["delvalue"];
if(i==1)
{
msg = "Record is Deleted";
}
else
{
msg = "Record is not Deleted";
}
}
}
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<form name="myform" method="post" action="~/Emp/Index">
<div>
Select DeptNo:
<select name="DropDnosList" onchange="submit()">
<option>-select-</option>
@foreach (int dno in ViewBag.dnos)
{
<option>@dno</option>
}
</select>
<br /><br />
Select EmpNo:
<select name="DropEnosList">
<option>-select-</option>
@{
if (this.IsPost)
{
foreach (int eno in ViewBag.enos)
{
<option>@eno</option>
}
}
}
</select>
<br /><br />
<input name="btnDelete" type="submit" value="Delete"
formaction="~/Emp/Delete" />
<br /><br />
@Html.Label("lblMsg", msg)
</div>
</form>
</body>
128 | P a g e
ASP.NET MVC MR.R.N.REDDY
</html>
Controller=”Emp”
Example to update the record by using drop down list and Entity frame work
Update
Salary is Updated
return dnos;
129 | P a g e
ASP.NET MVC MR.R.N.REDDY
return enos;
objemp.empsal = Esal;
try
objcomp.SaveChanges();
return 1;
catch
return 0;
130 | P a g e
ASP.NET MVC MR.R.N.REDDY
ForwardDrops();
return View();
[HttpPost]
objmodel.Dno = int.Parse(Request["DropDnosList"]);
ForwardDrops();
return View("Index");
[HttpPost]
@{
Layout = null;
string msg = "";
if(this.IsPost)
{
131 | P a g e
ASP.NET MVC MR.R.N.REDDY
if(Request["btnUpdate"]=="Update")
{
int i = (int)ViewData["updatevalue"];
if(i==1)
{
msg = "Salary is Updated";
}
else
{
msg = "Salary is not Updated";
}
}
}
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<form name="myform" method="post" action="~/Emp/Index">
<div>
Select DeptNo:
@Html.DropDownList("DropDnosList", null, "-select-",
htmlAttributes: new { onchange = "submit()" })
<br /><br />
Select EmpNo:
@Html.DropDownList("DropEnosList", "-select-")
<br /><br />
Enter New Salary @Html.TextBox("txtNewSal")
<br/><br/>
<input name="btnUpdate" type="submit" value="Update"
formaction="~/Emp/Update" />
<br /><br />
@Html.Label("lblMsg", msg)
</div>
</form>
</body>
</html>
Controller=”Emp”
Record is Deleted
133 | P a g e
ASP.NET MVC MR.R.N.REDDY
@{
Layout = null;
string msg = "";
if (this.IsPost)
{
int i = (int)ViewData["delvalue"];
if (i == 1)
{
msg = "Record is Deleted";
}
else
{
msg = "Record is not Deleted";
}
}
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<form name="myform" method="post">
<div>
<table border="1">
<tr>
<th>Employee No</th>
<th>Employee Name</th>
<th>Employee Salary</th>
<th>Delete</th>
134 | P a g e
ASP.NET MVC MR.R.N.REDDY
</tr>
@{
foreach (var item in ViewBag.emp)
{
<tr>
<td>@item.Eno</td>
<td>@item.Ename</td>
<td>@item.salary</td>
<td>@Html.ActionLink("Delete", "DeleteEmp", new {eno=item.Eno})</td>
</tr>
}
}
</table>
@Html.Label("lblMsg",msg)
</div>
</form>
</body>
</html>
Controller=”Emp”
Record is Inserted
135 | P a g e
ASP.NET MVC MR.R.N.REDDY
[HttpPost]
public ActionResult Insert()
{
objmodel.Eno = int.Parse(Request["txtEno"]);
objmodel.Ename = Request["txtEname"];
objmodel.Esal = decimal.Parse(Request["txtEsal"]);
ViewData["insertvalue"] = objmodel.InsertEmp();
ForwardEmp();
return View("Index");
}
136 | P a g e
ASP.NET MVC MR.R.N.REDDY
@{
Layout = null;
string msg = "";
if (this.IsPost)
{
int i = (int)ViewData["insertvalue"];
if (i == 1)
{
msg = "Record is Inserted";
}
else
{
msg = "Record is not Inserted";
}
}
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<form name="myform" method="post">
<div>
<table border="1">
<tr>
<th>Employee No</th>
<th>Employee Name</th>
<th>Employee Salary</th>
<th>Insert</th>
</tr>
@{
foreach (var item in ViewBag.emp)
{
<tr>
<td>@item.Eno</td>
<td>@item.Ename</td>
<td>@item.salary</td>
</tr>
}
}
<tr>
<td>@Html.TextBox("txtEno")</td>
<td>@Html.TextBox("txtEname")</td>
137 | P a g e
ASP.NET MVC MR.R.N.REDDY
<td>@Html.TextBox("txtEsal")</td>
Controller=”Emp”
Salary is Updated
138 | P a g e
ASP.NET MVC MR.R.N.REDDY
[HttpPost]
public ActionResult Update()
{
objmodel.Eno = int.Parse(Request["txtEno"]);
objmodel.Esal=decimal.Parse(Request["txtNewSal"]);
ViewData["updatevalue"] = objmodel.UpdateEmp();
ForwardEmp();
return View("Index");
}
139 | P a g e
ASP.NET MVC MR.R.N.REDDY
@{
Layout = null;
string msg = "";
if (this.IsPost)
{
if(Request["btnUpdate"]=="Update")
{
int i = (int)ViewData["updatevalue"];
if (i == 1)
{
msg = "Salary is Updated";
}
else
{
msg = "Salary is not Updated";
}
}
}
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<form name="myform" method="post">
<div>
<table border="1">
<tr>
<th>Employee No</th>
<th>Employee Name</th>
<th>Employee Salary</th>
<th>Edit</th>
</tr>
@{
foreach (var item in ViewBag.emp)
{
<tr>
<td>@item.Eno</td>
<td>@item.Ename</td>
<td>@item.salary</td>
<td>@Html.ActionLink("Edit", "EditEmp", new { eno = item.Eno })</td>
</tr>
}
}
</table>
@Html.Label("lblMsg", msg)
140 | P a g e
ASP.NET MVC MR.R.N.REDDY
</div>
</form>
</body>
</html>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Update</title>
</head>
<body>
<form name="myform1" method="post">
<div>
<table border="1">
<tr>
<th>Employee No</th>
<th>Employee Name</th>
<th>Employee Salary</th>
<th>Update/Cancel</th>
</tr>
@{
foreach (var item in ViewBag.emp)
{
if(item.Eno.ToString()==Request.QueryString["eno"])
{
<tr>
<td><input type="text" name="txtEno" [email protected] readonly /></td>
<td>@item.Ename</td>
<td><input type="text" name="txtNewSal" [email protected] /></td>
<td><input type="submit" name="btnUpdate" value="Update"
formaction="~/Emp/Update" />
@Html.ActionLink("Cancel", "Cancel")</td>
</tr>
}
else
{
<tr>
<td>@item.Eno</td>
<td>@item.Ename</td>
<td>@item.salary</td
<td>@Html.ActionLink("Edit", "EditEmp", new { eno = item.Eno })</td>
</tr>
}
141 | P a g e
ASP.NET MVC MR.R.N.REDDY
}
}
</table>
</div>
</form>
</body>
</html>
Controller=”Emp”
Enter UserId :
Enter Password :
Login
Welcome.cshtml
Logout
142 | P a g e
ASP.NET MVC MR.R.N.REDDY
[HttpPost]
public ActionResult Welcome()
{
Login objmodel = new Login
{
UName = Request["txtUname"],
UPwd = Request["txtPwd"]
};
ViewBag.user = objmodel.GetUser();
if (ViewBag.user != null)
{
return View("Welcome");
143 | P a g e
ASP.NET MVC MR.R.N.REDDY
}
else
{
return View("Login");
}
}
}
@model MVCLoginEFNormalTextBox.Models.Login
@{
Layout = null;
if (this.IsPost)
{
if (ViewBag.user == null)
{
<script type="text/javascript">
alert("Invalid User")
</script>
}
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Login</title>
</head>
<body>
<form name="myform" method="post">
<div>
Enter Username @Html.TextBox("txtUname")
<br /><br />
Enter Password @Html.TextBox("txtPwd")
<br /><br />
<input name="btnLogin" type="submit" value="Login"
formaction="~/Login/Welcome" />
</div>
</form>
</body>
</html>
Step-6: Adding View
144 | P a g e
ASP.NET MVC MR.R.N.REDDY
<div>
<table border="1">
<tr>
<th>User ID</th>
<th>Name</th>
<th>User Name</th>
<th>User Pwd</th>
<th>User Hint</th>
</tr>
@foreach (var item in ViewBag.user)
{
<tr>
<td>@item.userid</td>
<td>@item.name</td>
<td>@item.username</td>
<td>@item.userpwd</td>
<td>@item.userhint</td>
</tr>
}
</table>
<br/><br/><br/>
@Html.ActionLink("Logout","LogoutUser")
</div>
</form>
Controller=”Login”, action=Login”
145 | P a g e
ASP.NET MVC MR.R.N.REDDY
Go to Solution Explorer
Go to Views folder and expand Views folder
Right click on Shared folder
Add -> New Item
It will open new item window
Select MVC 4 Layout Page(Razor)
Rename it as _MasterPage1.cshtml
Click add
By this process we added master page
Write Code like below
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>@ViewBag.Title</title>
146 | P a g e
ASP.NET MVC MR.R.N.REDDY
</head>
<body>
<header style=" background-color:gray;text-align:center">
<h1 style="color:white">Welcome To Sathya Technologies</h1>
</header>
<nav style="background-color:lightskyblue;text-align:center;color:green">
<div>
@Html.ActionLink("Home", "Login", "Home")
@Html.ActionLink("About US", "AboutUs", "Home")
@Html.ActionLink("Logout", "Logout", "Home")
</div>
</nav>
<div style="color:brown;background-color:lightgreen">
@RenderSection("DailyChangableContent",true)
</div>
<br /><br />
<br /><br />
<div>
@RenderBody()
</div>
<br/><br/>
<br/><br/>
<footer style="background-color:gray;text-align:center">
<h4 style="color:white">copyrights@sathyatechnologies</h4>
</footer>
</body>
</html>
Some important points (for MasterPage):-
Nav- Nav tags are generally used for navigation bar. We can add links to navigate between
the pages.
@RenderSection- Render section is just like a place holder where we can place our code
that we can inject from the content page. If we make render section property true, we must
need to add this section in all the pages which are used in this layout page, otherwise it will
go through as a not implemented error. If we want to make this an option, we need to set it
to false.
Header & Footer- These are useful to display the header and footer information.
Layout
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVCMasterPage.Controllers
147 | P a g e
ASP.NET MVC MR.R.N.REDDY
{
public class HomeController : Controller
{
public ActionResult Login()
{
return View();
}
public ActionResult Welcome()
{
return View("Welcome");
}
public ActionResult AboutUs()
{
return View("Login");
}
public ActionResult Logout()
{
return View("Login");
}
}
}
Go to controller
Right click on Login method
Click on Add View
Rename it as Login
Check “use a Layout or MasterPage” at bottom
Click on browse button
Select MasterPage1 in Views Folder-> Shared Folder
Click Add
By this process we added Child page for MasterPage1
Login.cshtml:-
@{
ViewBag.Title = "Login";
Layout = "~/Views/Shared/_MasterPage1.cshtml";
}
@section DailyChangableContent{
<h3 style="text-align:center">@DateTime.Today.ToShortDateString()</h3>
}
<br /><br />
<form name="myform" method="post">
<div style="text-align:center;top:200px;border:double;background-
color:lightgray;width:350px;margin-left:500px;color:blue">
148 | P a g e
ASP.NET MVC MR.R.N.REDDY
<h2>Login</h2>
Enter Username @Html.TextBox("txtUName", null, new { style =
"color:red" })
<br /><br />
Enter Password @Html.Password("txtUPwd", null, new { style =
"color:red" })
<br /><br />
<input type="submit" name="btnLogin" style="color:aqua;background-
color:blueviolet" formaction="~/Home/Welcome" />
<br/><br/>
</div>
</form>
Welcome.cshtml:-
@{
ViewBag.Title = "Welcome";
Layout = "~/Views/Shared/_MasterPage1.cshtml";
}
@section DailyChangableContent{
<h3 style="text-align:center">@DateTime.Today.Date.ToShortDateString()</
h3>
}
<div>
<h2 style="text-align:center">Welcome User</h2>
</div>
Step-5:- Update RouteConfig.cs
Bundling:
What is bundling?
Bundling allows us to load the bunch of static files from the server into one HTTPRequest
149 | P a g e
ASP.NET MVC MR.R.N.REDDY
In the above diargarm browser sends 2 separate requests to load 2 different javascript files i.e
Myjavascriptfile-1.js and Myjavascriptfile-2.js
Bundling technique in MVC 4 allows us to load more than one javascript file i.e Myjavascriptfile-1.js
and Myjavascriptfile-2.js in one request as shown below
What is Minification:
Minification is a technique which optimises script or css file size by removing unneccesary
sayHello=function(name)
//this is comment
Var msg=”hello”+name;
150 | P a g e
ASP.NET MVC MR.R.N.REDDY
alert(msg);
The above javascript file will be optimiszedand minimiszedinto the following script.
sayHello=function(n){var t=”hello”+n;alert(t)}
As in the above code,it has removed unnecessarywhite space,comments and also shortening
variable names to reduce the characters which in turn will reduce the size of the javascript file.
Conclusion:
Bundling&Mining impacts on the loading of the page,it loads page faster by minimising size of the
file and numbers of requests.
Bundle Types:
MVC5 includes following bundule classes in System.Web.Optimization base base class library.
ScriptBundle:
StyleBundle:
StyleBundle is responsible for CSS minification of single or multiple style sheet files.
It represents a bundle that ASP.NET creates from a folder that contains the same type .
Routing:
Note :Routing is not a specific to Mvc Frame Work it can be used with Asp.Net Web form application
(or) Asp.Net Mvc application
What is Routing?
It Asp.Net every request will contain like below Http://Domain/StudentInfo.aspx. means in Asp.Net
request it is targeted the .aspx file due to that reason the URL are file based URL’s . To that reason
the Url are file based url’s to avoid mapping each Url with a physical file in Asp.Net Mvc introduced a
new concept called Routing,
151 | P a g e
ASP.NET MVC MR.R.N.REDDY
In Mvc Routing enables us to define Url pattern that mapes to the request handler.
In Asp.Net request handler is .Aspx file but In MVC request handler is Controller class and Action
method.
What is Route?
Route defines the Url pattern and handler information, All the configured routes of an application
stored in internally route table and will be used by Routing engine to determine appropriate
152 | P a g e
ASP.NET MVC MR.R.N.REDDY
Configured Route?
Every Mvc application must configured atlest one route which is configured by Mvc Frame
Work by default.
You can registered a route with in routeConfiged class which is in RouteConfig.Cs under
App.Start folder.
The following diagram represent How to Configure a route with in the RouteConfig class.
Routes.Ignore(“{resourse}.axd/{*pathInfo}”);
Routes.MapRoute(name:”Default”,Url:”{Controller}/{action}/{id}”
defaults:new{Controller=”Home”,action=”Index”,id=”urlparameter.optional”}
);
}//method
}//class
Filters in MVC:
1. Authentication Filters.
2. Authorization Filters.
3. Action Filters.
4. Result Filters.
5. Exception Filters.
1.Authentication Filters.
153 | P a g e
ASP.NET MVC MR.R.N.REDDY
2.Authorization Filters.
Authorization filters are responsible for checking user access these implements the
“IAuthorizatuionFilter” interface with in the Frame Work
3.Action Filters.
Action Filters can Apply on Entire Controller or Single Action Methods. these filters will be
called before after the action Start Execution and After the action has Executed.
These Action Filters contain logic i.e. executed before anf after a Controller Action Execute.
you can use an action filters to modify the view data that a controller action returns. Inter
Face of action Filters is “IActionFilter”.
4.Result Filters:
These filters contain logic i.e. executed before and after a view result is Exected.
That means result filterwill execute before view result and after view result. Interface of
result filter is :”IResultFilter”.
5.Exeception Filter:
Exception Filter will execute if there are any unhandled exception throw during the
execution.
These filters can be used to handled error rised by either your Controller action (or)
Controller action result.
154 | P a g e
ASP.NET MVC MR.R.N.REDDY
RN Reddy IT School
For Training’s contact
Cell: +91 9966640779, 9885199122 &9866183094
E-Mail:[email protected]
Website: www.rnreddyitschool.co
FaceBook Group:https://www.facebook.com/groups/rnreddytechsupports
FaceBook Page:https://www.facebook.com/groups/reddyitschool
Youtube Channel:-https://www.youtube.com/c/RNREDDYITSchool
155 | P a g e