MVC
MVC stands for Model, View and Controller.
Model represents the data
View is the User Interface.
Controller is the request handler.
MVC-MVC 5 is a web framework based on Mode-View-Controller
(MVC) architecture. Developers can build dynamic web applications using ASP.NET
MVC framework that enables a clean separation of concerns, fast development,
and TDD friendly.
Model: Model represents the shape of the data. A
class in C# is used to describe a model. Model objects store data retrieved
from the database.
View: View in MVC is a user interface. View display
model data to the user and also enables them to modify them. View in ASP.NET
MVC is HTML, CSS, and some special syntax (Razor syntax) that makes it easy to
communicate with the model and the controller.
Controller: The controller handles the user request.
Typically, the user uses the view and raises an HTTP request, which will be
handled by the controller. The controller processes the request and returns the
appropriate view as a response.
Advantages of MVC
Separation Of Concern (SOC) is the main advantage. Here we
are separating Mode, View, and Controller.
We can easily maintain MVC application.
Test Drive Development (TDD) is another main advantage. We
can create an application with a unit
We can write our own test case.
Split the application and many developers can work at a time
without affecting each other.
MVC application is a default responsive web site and mobile
template.
We can create our own view engine.
A Controller handles incoming URL requests. MVC routing
sends request to appropriate controller and action method based on URL and
configured Routes.
All the public methods in the Controller class are called
Action methods.
A Controller class must be derived from
System.Web.Mvc.Controller class.
A Controller class name must end with
"Controller".
New controller can be created using different scaffolding
templates. You can create custom scaffolding template also.
ACTION METHOD :- All
the public methods of a Controller class are called Action methods. They are
like any other normal methods with the following restrictions:
Action method must be public. It cannot be private or
protected.
Action method cannot be overloaded.
Action method cannot be a static method.
How to create new MVC project
Create new project
C# /All Platform/ Web /Asp.net web application --àcreate
Enter project name / select MVC
Right click – Controllers from Solution
Explorer/Add/Controller/MVC 5 controller-Empty/Controller name As
DefaultController as MyHomeController
Eg1.
namespace MVC1.Controllers
{
public class MyHomeController : Controller
{
// GET: MyHome
public ActionResult
Index()
{
return View();
}
public String one()
{
return "WELCOME";
}
}
}
Eg2.
public String one()
{
return "<b><i><u>WELCOME</u></i></b>";
}
Eg3.
public string GetAllCustomers()
{
return @"<ul>
<li>Ali
Raza</li>
<li>Mark
Upston</li>
<li>Allan
Bommer</li>
<li>Greg
Jerry</li>
</ul>";
}
Eg4.
public string
GetAllCustomers()
{
return @"<ol>
<li>Ali
Raza</li>
<li>Mark
Upston</li>
<li>Allan
Bommer</li>
<li>Greg
Jerry</li>
</ol>";
}
Eg5.
namespace MVC1.Controllers
{
public class Home1Controller : Controller
{
// GET: Home1
public ActionResult
Index()
{
return View();
}
public string mytime()
{
return
DateTime.Now.ToString("T");
}
}
}
Eg6.
public string mydate()
{
return
DateTime.Now.ToString("D");
}
Eg7.
public string dates()
{
return DateTime.Now.ToShortDateString();
}
VIEW
View is a user interface. View displays data from the model
to the user and also enables them to modify the data.
Razor View Engine
Microsoft introduced the Razor view engine and packaged with
MVC 3. You can write a mix of html tags and server side code in razor view.
Razor uses @ character for server side code instead of traditional <% %>.
You can use C# or Visual Basic syntax to write server side code inside razor
view. Razor view engine maximize the speed of writing code by minimizing the
number of characters and keystrokes required when writing a view. Razor views
files have .cshtml or vbhtml extension.
Right click index() in the MyHome controller page, then add
view, click Add, we get Index.cshtml.
Eg1.
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<h3>Good Afternoon</h3>
Main Razor Syntax Rules for C#
Razor code blocks are enclosed in @{ ... }
Inline expressions (variables and functions) start with @
Code statements end with semicolon
Variables are declared with the var keyword
Strings are enclosed with quotation marks
C# code is case sensitive
C# files have the extension .cshtml
Razor Keywords
functions
inherits
model
section
Eg1.
@{
ViewBag.Title =
"Index";
}
<h2>Index</h2>
<h4>I am a view</h4>
<h1>Razor syntax demo</h1>
<h2>@DateTime.Now.ToShortDateString()</h2>
@{
var date =
DateTime.Now.ToShortDateString();
var message =
"Hello World";
}
<h2>Today's date is: @date </h2>
<h3>@message</h3>
Eg2.
@{
Layout = null;
var name =
"Jaseena";
}
<!DOCTYPE html>
<html>
<head>
<meta
name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<h2>My name
is @name </h2>
</body>
</html>
Eg4.
@{
Layout = null;
var name = "Jaseena";
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Anchu</title>
</head>
<body>
<h2>My name is @name </h2>
</body>
</html>
Eg5.
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta
name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<p>Current
Time is: @DateTime.Now.ToString("T")</p>
</body>
</html>
Eg6:
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>2 + 5 = @(2+5)</p>
Operators
1. Math operators
+,-,*,/
Eg1:
<html>
<head> <title>MathOperators</title> </head>
<body>
@{
int num1, num2, plus, minus, multi, divide;
num1= 45;
num2= 9;
plus= num1 + num2;
minus= num1 - num2;
multi= num1 * num2;
divide= num1 / num2;
}
<h5>Addition :@num1 + @num2 = @plus</h5>
<h5>Subtraction :@num1 - @num2 = @minus</h5>
<h5>Multiplication: @num1 * @num2 = @multi</h5>
<h5>Divide :@num1 / @num2 = @divide</h5>
</body>
</html>
2. Assignment Operator
=
3. Equality operator
==
4. InEquality operator
!=
Eg:
<html>
<head>
<title>Inequality Operator </title>
</head>
<body>
@{
int num1 =
5, num2 = 10;
if(num1 !=
num2)
{
<h5>Returns True</h5>
}
}
</body>
</html>
Eg2:
<h2>Index</h2>
<html>
<head>
<title>Inequality
Operator </title>
</head>
<body>
@{
int num1 = 5, num2
= 5;
if (num1 != num2)
{
<h5>Returns True</h5>
}
else
{
<h5>Returns False</h5>
}
}
</body>
</html>
5. Comparision operator
<, >, <=, >=
Eg1:
<html>
<head>
<title>Comparison
Operator </title>
</head>
<body>
@{
int num1 = 5, num2 =
10;
if(num1 < num2)
{
<h5>@num1 is less than
@num2</h5>
}
else
{
<h5>@num1
is greater than @num2</h5>
}
}
</body>
</html>
Eg2:
<h2>Index</h2>
<html>
<head>
<title>Comparison
Operator </title>
</head>
<body>
@{
int num1 = 5, num2
= 5;
if (num1 <=
num2)
{
<h5>@num1 is less than or equal to @num2</h5>
}
else
{
<h5>@num1 is greater
than @num2</h5>
}
}
</body>
</html>
Increment and decrement operator
++ ,+= ,-- , -=
Eg:
<html>
<head>
<title>Increment
and Decrement Operators</title>
</head>
<body>
@{
int inc = 5;
<h3>Increment
of @inc is @{inc++;} : @inc</h3>
<h3>Decrement
of @inc is @{inc--;} : @inc</h3>
<h3>Increment
of @inc is @{inc+=1;} : @inc</h3>
<h3>Decrement
of @inc is @{inc-=1;} : @inc</h3>
}
</body>
</html>
Concatenation operator
@{
ViewBag.Title = "Index";
}
<html>
<head>
<title>Concatenation
Operator</title>
</head>
<body>
@{
string msg1 = "Hello";
string msg2 = "Trivandrum";
string finalmsg =
msg1 + " " + msg2;
}
<h3>@finalmsg</h3>
</body>
</html>
Dot Operator
It is used to distinguish objects and
their properties and methods.
Eg:
<html>
<head>
<title>Dot
Operator</title>
</head>
<body>
@{
var num = "55";
int i;
i=num.AsInt();
<h3>@i</h3>
<h3>Browser Name :
@Request.Browser.Id</h3>
}
</body>
</html>
Parentheses :
It is () . It is used to group
expression and to pass parameters to methods.
Eg:
<html>
<head>
<title>Parentheses</title>
</head>
<body>
@{
int num1 = 5, num2 = 10;
if((num1 + num2) == 15)
{
<h2>Addition is 15</h2>
}
}
</body>
</html>
Bracket
It is []. It is used for accessing value in
arrays of collections.
Eg:
<html>
<head>
<title>Bracket</title>
</head>
<body>
@{
int[] arr={12,562,62,98,388};
<h3>@arr[3]</h3>
}
</body>
</html>
Not Operator : It is ! (Not). It reverse true
into false and false into true.
Eg:
<html>
<head>
<title>Not
Operator</title>
</head>
<body>
@{
int num1 = 5, num2 = 10;
if(!(num1 == num2))
{
<h3>However conditions
are false still this message appears because you have used not operator and it
reverse the condition.</h3>
}
}
</body>
</html>
Logical Operator :
It is && (AND) and || (OR). It is used
to link conditions together and helps to make logic much better.&& -
Returns true if all the specified conditions are true otherwise returns false.
|| - Returns true if one or all the
conditions are true.
Eg:
<html>
<head>
<title>Logical Operator
</title>
</head>
<body>
@{
string username =
"hello";
string password =
"tvm";
if(username ==
"Steven" && password == "Svn78*")
{
<h3>Login
Successful</h3>
}
else if(username ==
"Steven" || password == "12345")
{
<h3>Hello Steven, you
have entered wrong password.</h3>
}
else
{
<h3>Unauthorized
Login</h3>
}
}
</body>
</html>
Eg2:
<html>
<head>
<title>Logical
Operator </title>
</head>
<body>
@{
string username = "hello";
string password = "tvm";
if (username == "hello1" &&
password == "tvm1")
{
<h3>Login Successful</h3>
}
else if (username == "hello" || password == "12345")
{
<h3>Hello, you have entered wrong password.</h3>
}
else
{
<h3>Unauthorized Login</h3>
}
}
</body>
</html>
Eg:
<html>
<head>
<title>Math Operators</title>
</head>
<body>
@{
int num1, num2, plus, minus, multi,
divide;
num1 = 45;
num2 = 9;
plus = num1 + num2;
minus = num1 - num2;
multi = num1 * num2;
divide = num1 / num2;
}
<h5>Addition : @num1 + @num2 = @plus</h5>
<h5>Subtraction : @num1 - @num2
= @minus</h5>
<h5>Multiplication : @num1 * @num2
= @multi</h5>
<h5>Divide : @num1 / @num2 =
@divide</h5>
</body>
</html>
Alert Box
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport"
content="width=device-width" />
<title>Index</title>
</head>
<body>
<script>alert('System Failure!')</script>
</body>
</html>
Loop
1. For Loop
Eg:
<body>
@for (var i
= 0; i < 5; i++)
{
<text>i= @i </text> <br/>
}
</body>
2. If else
<h2>IfElse</h2>
@{
ViewBag.Title = "TECHZMATRIX";
var value = 20;
}
<hr />
@if (value >
100)
{
<p>This value is
greater than 100.</p>
}
else
{ <p>This value is less than 100.</p>
}
Eg2:
@{
var
txt = "";
if(DateTime.Now.Hour
> 12)
{txt
= "Good Evening";}
else
{txt
= "Good Morning";}
}
<html>
<body>
<p>The
message is @txt</p>
</body>
</html>
Eg3:
@if(DateTime.IsLeapYear(DateTime.Now.Year)
)
{
@DateTime.Now.Year @:is a leap year.
}
else
{
@DateTime.Now.Year @:is not a leap year.
}
3. If else if
Eg1:
@{var
price=25;}
<html>
<body>
@if
(price>=30)
{
<p>The price is high.</p>
}
else
if (price>20 && price<30)
{
<p>The price is OK.</p>
}
else
{
<p>The price is low.</p>
}
</body>
</html>
4. Swich case
Eg1:
@{
ViewBag.Title = "TST";
var
value = 20;
}
<hr />
@switch (value)
{
case 1:
<p>You Entered 1</p>
break;
case 25:
<p>You Entered 25</p>
break;
default:
<p>You entered something than 1 and 25.</p>
break;
}
Eg2:
@{
string day = DateTime.Now.DayOfWeek.ToString();
switch (day)
{
case "Monday":
<h3>It's Monday</h3>
break;
case "Tuesday":
<h3>It's Tuesday</h3>
break;
case "Wednesday":
<h3>It's Wednesday</h3>
break;
case "Thursday":
<h3>It's Thursday</h3>
break;
case "Friday":
<h3>It's Friday</h3>
break;
case "Saturday":
<h3>It's Saturday</h3>
break;
case "Sunday":
<h3>It's Sunday</h3>
break;
default:
<h3>What! Ok! Its Funday</h3>
break;
}
}
5. For Each Loops
If you work with a collection or an array, you often use a
for each loop.
A collection is a group of similar objects, and the for each
loop lets you carry out a task on each item. The for each loop walks through a
collection until it is finished. Foreach loop is used when you are working with
collections or an array.
The example below walks through the ASP.NET
Request.ServerVariables collection.
Eg1:
@{
ViewBag.Title = "foreachloop";
}
<h2>foreachloop</h2>
<html>
<body>
<ul>
@foreach (var x in
Request.ServerVariables)
{
<li>@x</li>
}
</ul>
</body>
</html>
Eg2:
<html lang="en">
<head>
<meta
charset="utf-8" />
<title></title>
</head>
<body>
@{
int[]
arr={1,3,5,7,11,13,17,19};
foreach(int
x in arr)
{
<span>@x, </span>
}
}
</body>
</html>
Eg3:
@{
string[] members = {"Achu", "Rakesh",
"jani", "kashi"};
int i = Array.IndexOf(members, "jani")+1;
int len = members.Length;
string x = members[2-1];
}
<html>
<body>
<h3>Members</h3>
@foreach (var person in members)
{
<p>@person</p>
}
<p>The number of names in Members are @len</p>
<p>The person at position 2 is @x</p>
<p>Jani is now in position @i</p>
</body>
</html>
Two
Dimensional array
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<h3>Multi Dimensional Array</h3>
@{
string[,] letter=new string[3,2] {{"a","b"},{"c","d"},{"e","f"}};
for(int i=0; i<3;
i++) { for(int j=0; j<2; j++)
{
<span>@letter[i,j], </span>
}
<br />
}
}
6. While loop
The while loop is a general purpose loop.
A while loop begins with the while keyword,
followed by parentheses, where you specify how long the loop continues, then a
block to repeat.
While loops typically add to, or subtract from, a
variable used for counting.
Syntax
while(condition)
{
stmts;
}
Eg:
<html>
<body>
@{
var
i = 0;
while
(i < 5)
{
i += 1;
<p>Line @i</p>
}
}
</body>
</html>
Do while
do{stmts;
}
while(condition);
eg:
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<html>
<body>
@{
var i = 0;
do
{
i += 2;
<p>Even @i</p>
}
while (i <= 20);
}
</body>
</html>
Razor HTML Helpers
HtmlHelper
is a class which is introduced in MVC 2. It is used to create HTML controls
programmatically. It provides built-in methods to generate controls on the view
page. In this topic we have tabled constructors, properties and methods of this
class. At the end, we have explained an example that creates a form with the
help of extension methods.
Eg:
//Controller
code
public
ActionResult HtmlHelperDemo()
{
return View();
}
[HttpPost]
public ContentResult UserRegistration()
{
return Content(
"User Name = " +
Request.Form["username"] + "<br/>" +
"Email ID = " + Request.Form["email"] +
"<br/>" +
"Gender = " + Request.Form["gender"]
+ "<br/>" +
"Courses = " +
Request.Form.GetValues("C#")[0] + " " +
Request.Form.GetValues("ASP.NET")[0] + " " + Request.Form.GetValues("ADO.NET")[0]
+ "<br/>" +
"Contact = " + Request.Form["contact"]
+ "<br/>"
);
}
}
}
//
View code
@{
ViewBag.Title = "HtmlHelperDemo";
}
<h2>HtmlHelperDemo</h2>
@{
ViewBag.Title = "HtmlHelperDemo";
}
<hr
/>
<h3>User
Registration Form</h3>
<hr
/>
<div
class="form-horizontal">
@using
(Html.BeginForm("UserRegistration", "third"))
{
<div
class="form-group">
@Html.Label("User Name",
new { @class = "control-label col-sm-2" })
<div
class="col-sm-10">
@Html.TextBox("username", null, new { @class =
"form-control" })
</div>
</div>
<div
class="form-group">
@Html.Label("Email ID",
new { @class = "control-label col-sm-2" })
<div
class="col-sm-10">
@Html.TextBox("email", null, new { @class =
"form-control" })
</div>
</div>
<div
class="form-group">
@Html.Label("Gender", new
{ @class = "control-label col-sm-2" })
<div>
<div
class="col-sm-10">
Male
@Html.RadioButton("Gender", "male")
Female
@Html.RadioButton("Gender", "female")
</div>
</div>
</div>
<div
class="form-group">
@Html.Label("Courses",
new { @class = "control-label col-sm-2" })
<div
class="col-sm-10">
C#
@Html.CheckBox("C#", new { value = "C#" })
ASP.NET
@Html.CheckBox("ASP.NET", new { value = "ASP.NET" })
ADO.NET
@Html.CheckBox("ADO.NET", new { value = "ADO.NET" })
</div>
</div>
<div
class="form-group">
@Html.Label("Contact", new { @class = "control-label
col-sm-2" })
<div
class="col-sm-10">
@Html.TextBox("contact", null, new { @class =
"form-control" })
</div>
</div>
<div
class="form-group">
<div
class="col-sm-2"></div>
<div
class="col-sm-10">
<input
type="submit" value="submit" class="btn
btn-primary" />
</div>
</div>
}
</div>
Eg2:
//controller
public class AdditionController : Controller
{
// GET:
Addition
public ActionResult
Index(int firstnumber = 0, int secondnumber = 0)
{
int result =
firstnumber + secondnumber;
ViewBag.res =
result;
return View();
}
}
//view
code
<form
action="" method="post">
first number :<input
id="firstnumber" name="firstnumber" type="text"
/><br />
Second number :<input
id="secondnumber" name="secondnumber" type="text"
/><br />
<input id="Submit1"
type="submit" value="submit" />
Sum= @ViewBag.res
</form>
COLLECTION:-
A
collection is a group of objects of the same type. There are mainly two common
collections are used in razor, Array and Dictionary.
DICTIONARY
A
dictionary is a collection of key/value pairs.
Eg:
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
@{
var result = new Dictionary<string, int>();
result.Add("anchu", 75);
result.Add("rakesh", 80);
result.Add("kashi", 95);
}
<h3>Results of the
students are:</h3>
<h3>Anchu : @result["anchu"]</h3>
<h3>Rakesh : @result["rakesh"]</h3>
<h3>Kashi : @result["kashi"]</h3>
</body>
</html>
Function
<html
lang="en">
<head>
<meta charset="utf-8"
/>
<title></title>
</head>
<body>
@functions{
public int sum(int x, int y)
{
return x+y;
}
}
<h3>Add of 5 + 6 is
@sum(5,6)</h3>
<h3>Add of 9 + 10 is
@sum(9,10)</h3>
</body>
</html>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
@functions{
public int sum(int x, int y)
{
return x + y;
}
public int product(int x, int y, int z)
{
return x * y * z;
}
}
<h3>Add of 5 + 6 is
@sum(5, 6)</h3>
<h3>Add of 9 + 10
is @sum(9, 10)</h3>
<h3>Product of 5 *
5 * 5 is @product(5,
5, 5) </h3>
<h3>Product of 6 *
5 * 4 is @product(6,
5, 4) </h3>
</body>
</html
Exception Handling
<html
lang="en">
<head>
<meta charset="utf-8"
/>
<title></title>
</head>
<body>
@functions{
public int divide(int x, int y)
{
string errormessage;
try
{
return x/y;
}
catch(DivideByZeroException d)
{
errormessage =
d.ToString();
WriteLiteral("<br
/>Cannot Divide by Zero Exception found <br /><br />");
WriteLiteral("Additional Info <br /><br />" +
errormessage);
return 0;
}
}
}
<h3>Division of 10 / 5 is
@divide(10,5)</h3>
<h3>Add of 12 + 0 is
@divide(12,0)</h3>
</body>
</html>
Model
A
model is a class that contains the business logic of the application. It also
used for accessing data from the database. The model class does not handle
directly input from the browser. It does not contain any HTML code as well.
Models
are also refers as objects that are used to implement conceptual logic for the
application. A controller interacts with the model, access the data, perform
the logic and pass that data to the view.
Model
is a collection of classes wherein you will be working with data and business
logic. Hence, basically models are business domain-specific containers. It is
used to interact with database.
Eg: Right click Model/add class/then add classname
//model
public class AdditionViewModel
{
public double A
{
get;
set;
}
public double B
{
get;
set;
}
public double Result
{
get;
set;
}
}
}
//Controller
[HttpGet]
public ActionResult Index() {
return View();
}
[HttpPost]
public ActionResult
Index(AdditionViewModel model, string command) {
if (command == "add")
{
model.Result = model.A +
model.B;
}
if (command == "sub")
{
model.Result = model.A -
model.B;
}
if (command == "mul")
{
model.Result = model.A *
model.B;
}
if (command == "div")
{
model.Result = model.A /
model.B;
}
return View(model);
}
//View
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@model MVC1.Models.AdditionViewModel
@{
Layout = null;
}
@using
(Html.BeginForm())
{
<fieldset>
<h2 style="color:blue"> Operation Of
Two Numbers </h2>
@Html.EditorFor(x => x.A) <br /> <br /> @Html.EditorFor(x =>
x.B) <br />
<br /> <input type="submit" value="add" name="command" />
<input type="submit" value="sub" name="command" />
<input type="submit" value="mul" name="command" />
<input type="submit" value="div" name="command" /> <br /> <br />
<h2 style="color:red">
@Html.Label("Result
is :")
@Html.DisplayFor(x =>
x.Result)
</h2>
</fieldset>
}
Eg2: public class AdditionViewModel
{
public double A
{
get;
set;
}
public double B
{
get;
set;
}
public double C
{
get;
set;
}
public double Result
{
get;
set;
}
}
//Controller
public class AdditionModelController : Controller
{
// GET:
AdditionModel
[HttpGet]
public ActionResult
Index()
{
return View();
}
[HttpPost]
public ActionResult
Index(AdditionViewModel model, string command)
{
if (command == "average")
{
model.Result =
(model.A + model.B + model.C)/3;
}
if (command == "total")
{
model.Result =
model.A + model.B + model.C;
}
return View(model);
}
}
//view
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@model MVC1.Models.AdditionViewModel
@{
Layout = null;
}
@using
(Html.BeginForm())
{
<fieldset>
<h2 style="color:blue"> Operation Of
Two Numbers </h2>
@Html.EditorFor(x => x.A) <br /> <br /> @Html.EditorFor(x =>
x.B) <br /> <br/> @Html.EditorFor(x
=> x.C) <br />
<br /> <input type="submit" value="total" name="command" />
<input type="submit" value="average" name="command" />
<br /> <br />
<h2 style="color:red">
@Html.Label("Result
is :")
@Html.DisplayFor(x =>
x.Result)
</h2>
</fieldset>
}
Eg2:
//model
public class Customer
{
public int id { get; set; }
public string companyname { get; set; }
public string description { get; set; }
public string contactperson
{ get; set; }
public string contactnumber
{ get; set; }
}
}
//controller
public class customerController : Controller
{
// GET:
customer
public ActionResult
Index()
{
return View();
}
public ActionResult
ListCustomer()
{
List<Models.Customer> cust = new List<Models.Customer>();
cust.Add(new
Models.Customer() { id = 1, companyname = "TST", contactperson
= "sreeru", contactnumber
= "1234", description =
"software" });
cust.Add(new
Models.Customer() { id = 2, companyname = "TCS", contactperson
= "madhu", contactnumber
= "4567", description =
"marketing" });
return View(cust);
}
}
}
// View
@model IEnumerable<MVC1.Models.Customer>
@{
ViewBag.Title = "ListCustomer";
}
<h2>ListCustomer</h2>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model
=> model.companyname)
</th>
<th>
@Html.DisplayNameFor(model
=> model.description)
</th>
<th>
@Html.DisplayNameFor(model
=> model.contactperson)
</th>
<th>
@Html.DisplayNameFor(model
=> model.contactnumber)
</th>
<th></th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem
=> item.companyname)
</td>
<td>
@Html.DisplayFor(modelItem
=> item.description)
</td>
<td>
@Html.DisplayFor(modelItem
=> item.contactperson)
</td>
<td>
@Html.DisplayFor(modelItem
=> item.contactnumber)
</td>
</tr>
}
</table>
View Bag
The
ViewBag in ASP.NET MVC is used to transfer temporary data (which is not
included in the model) from the controller to the view.
ViewBag
only transfers data from controller to view, not visa-versa. ViewBag values
will be null if redirection occurs.
Eg1:
//model
namespace MVC1.Models
{
public class ItemList
{
public int ID { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public decimal Price { get; set; }
}
}
//controller
namespace MVC1.Controllers
{
public class ViewBagExampleController : Controller
{
// GET:
ViewBagExample
public ActionResult
Index()
{
ViewBag.ItemList
= "Computer
Shop Item List Page";
List<ItemList> IList = new List<ItemList>()
{
new ItemList
{ID=1, Name="iPhone", Category="Mobile", Price=2393 },
new ItemList
{ID=2, Name="HardDisk", Category="Computer", Price=9399 },
new ItemList
{ID=3, Name="Mouse", Category="Computer", Price=120 },
new ItemList
{ID=4, Name="Samsung Note3", Category="Mobile", Price=9348 }
};
return View(IList);
}
}
}
//View
@foreach
(var i in Model)
{
<h1>@ViewBag.ItemList</h1>
<b>ID : </b> @i.ID <br />
<b>Name : </b> @i.Name <br
/>
<b>Category : </b> @i.Category
<br />
<b>Price : </b> @i.Price <br
/>
<hr />
}
Eg2:
//view
<h1>@ViewBag.total</h1>
//controller
ViewBag.total = IList.Count();
//output
4
Eg3:
//model
public class User
{
public int ID { get; set; }
public string Name { get; set; }
}
}
//controller
namespace MVC1.Controllers
{
public class ViewBagExample2Controller : Controller
{
// GET: ViewBagExample2
public ActionResult
Index() //We'll set the ViewBag values in this action
{
ViewBag.Title = "TECHZMATRIX";
ViewBag.Description = "software training";
ViewBag.UserNow
= new User()
{
Name = "sree",
ID = 4,
};
return View();
}
}
}
//view
<h2>Index</h2>
<h3>@ViewBag.Title</h3>
<p>@ViewBag.Description</p>
Your name:
<div>
<dl>
<dt>Name:</dt>
<dd>@ViewBag.UserNow.Name</dd>
<dt>ID:</dt>
<dd>@ViewBag.UserNow.ID</dd>
</dl>
</div>
View Data
ViewData
is similar to ViewBag, which transfers data from Controller to View. ViewData
is of Dictionary type, whereas ViewBag is of dynamic type. However, both store
data in the same dictionary internally.
ViewData
is a dictionary, so it contains key-value pairs where each key must be a
string.
Eg:
//Model
namespace MVC1.Models
{
public class sum
{
public static int addition(int a, int b, int c)
{
return a + b + c;
}
}
}
//controller
namespace MVC1.Controllers
{
public class ViewDataController : Controller
{
// GET:
ViewData
public ActionResult Index(int n1, int n2, int n3)
{
ViewData["message"] = string.Format("{0}+{1}+{2}={3}", n1, n2, n3,
Models.sum.addition(n1, n2, n3));
return View();
}
}
}
//view
<h4>@ViewData["message"] </h4>
TempData
TempData
is used to transfer data from view to controller, controller to view, or from
one action method to another action method of the same or a different
controller.
TempData
stores the data temporarily and automatically removes it after retrieving a
value.
Eg:
Controller
namespace MVC1.Controllers
{
public class TempDataExampleController : Controller
{
// GET:
TempDataExample
public ActionResult
Index()
{
List<string> Courses = new List<string>();
Courses.Add("J2SE");
Courses.Add("J2EE");
Courses.Add("Spring");
Courses.Add("Hibernates");
TempData["Courses"] = Courses;
return View();
}
}
}
Index
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<ul>
@{
foreach (var Courses in TempData["Courses"] as List<string>)
{
<li> @Courses</li>
}
}
</ul>
Employee Controller
Model
public class Employee
{
public int EmployeeId { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
public string City { get; set; }
}
}
Controller
public class EmployeeController : Controller
{
// GET:
Employee
public ActionResult
Index()
{
return View();
}
public ActionResult
Details()
{
Employee
employee = new Employee()
{
EmployeeId =
101,
Name = "Jaseena",
Gender = "Female",
City = "TVM"
};
return
View(employee);
}
}
}
View
@model MVC1.Models.Employee
@{
ViewBag.Title = "Details";
}
<h2>Details</h2>
<table style="font-family:Arial">
<tr>
<td>
Employee ID:
</td>
<td>
@Model.EmployeeId
</td>
</tr>
<tr>
<td>
Name:
</td>
<td>
@Model.Name
</td>
</tr>
<tr>
<td>
Gender:
</td>
<td>
@Model.Gender
</td>
</tr>
<tr>
<td>
City:
</td>
<td>
@Model.City
</td>
</tr>
</table>
Page Linking
Eg:
Controller
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVC1.Controllers
{
public class MainController : Controller
{
// GET: Main
public ActionResult
Index()
{
return View();
}
public ActionResult
Home()
{
return View();
}
public ActionResult
About()
{
return View();
}
public ActionResult
Contactus()
{
return View();
}
}
}
View
- index
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<table cellspacing="20">
<tr>
<td>@Html.ActionLink("Mainpage", "Index")</td>
</tr>
<tr>
<td>@Html.ActionLink("Home page", "Home")</td>
</tr>
<tr>
<td>@Html.ActionLink("Contactus page", "Contactus")</td>
</tr>
<tr>
<td>@Html.ActionLink("About page", "About")</td>
</tr>
</table>
View- Home
@{
ViewBag.Title = "Home";
}
<h2>Home</h2>
<table cellspacing="20">
<tr>
<td>@Html.ActionLink("Mainpage", "Index")</td>
</tr>
<tr>
<td>@Html.ActionLink("Home page", "Home")</td>
</tr>
<tr>
<td>@Html.ActionLink("Contactus page", "Contactus")</td>
</tr>
<tr>
<td>@Html.ActionLink("About page", "About")</td>
</tr>
</table>
View
– About
@{
ViewBag.Title = "About";
}
<h2>About</h2>
<table cellspacing="20">
<tr>
<td>@Html.ActionLink("My Mainpage", "Index")</td>
</tr>
<tr>
<td>@Html.ActionLink("My Home page", "Home")</td>
</tr>
<tr>
<td>@Html.ActionLink("My Contactus page", "Contactus")</td>
</tr>
<tr>
<td>@Html.ActionLink("My About page", "About")</td>
</tr>
</table>
View- contact us
@{
ViewBag.Title = "Contactus";
}
<h2>Contactus</h2>
<table cellspacing="20">
<tr>
<td>@Html.ActionLink("Mainpage", "Index")</td>
</tr>
<tr>
<td>@Html.ActionLink("Home page", "Home")</td>
</tr>
<tr>
<td>@Html.ActionLink("Contactus page", "Contactus")</td>
</tr>
<tr>
<td>@Html.ActionLink("About page", "About")</td>
</tr>
</table>
MVC Redirect
method
public class RedirectController : Controller
{
// GET:
Redirect
public ActionResult
Index()
{
return Redirect("http://www.google.com");
}
}
}
Enum –
enumerated datatype
1. Right click Model folder/add new
model,name as Users
public class Users
{
public int UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime
BirthDate { get; set; }
public Role Role { get; set; }
}
public enum Role
{
Admin,
Normal,
Guest
}
2. Right
click Controller folder/Add Controller/Name as UserController.
namespace MVC1.Controllers
{
public class UserController : Controller
{
private readonly Users[]
userData =
{
new Users
{FirstName = "JASEENA", LastName = "ANSHAD", Role =
Role.Admin},
new Users
{FirstName = "ASEENA", LastName = "KOLLAM", Role =
Role.Admin},
new Users
{FirstName = "REEMA", LastName = "TVM", Role =
Role.Normal},
new Users
{FirstName = "AALIYA", LastName = "KANNUR", Role =
Role.Normal},
new Users
{FirstName = "VEDHA", LastName = "TVM", Role =
Role.Guest}
};
// GET: User
public ActionResult
Index()
{
return
View(userData);
}
public
PartialViewResult GetUserData(string selectedRole = "All")
{
IEnumerable data
= userData;
if (selectedRole
!= "All")
{
var selected =
(Role)Enum.Parse(typeof(Role), selectedRole);
data =
userData.Where(p => p.Role == selected);//LINQ-Language Intergrated Query
}
return
PartialView(data);
}
public ActionResult
GetUser(string selectedRole = "All")
{
return View((object)selectedRole);
}
}
}
3. Right click View folder/Add MVC 5
Partial Page/Name as GetUserData.
@model IEnumerable<MVC1.Models.Users>
<table>
<tr>
<th>
@Html.DisplayNameFor(model
=> model.FirstName)
</th>
<th>
@Html.DisplayNameFor(model
=> model.LastName)
</th>
<th>
@Html.DisplayNameFor(model
=> model.BirthDate)
</th>
<th></th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem
=> item.FirstName)
</td>
<td>
@Html.DisplayFor(modelItem
=> item.LastName)
</td>
<td>
@Html.DisplayFor(modelItem
=> item.BirthDate)
</td>
<td></td>
</tr>
}
</table>
4. Right click View folder/Add view/name
as GetUser
@using MVC1.Models
@model string
@{
ViewBag.Title = "GetUser";
AjaxOptions ajaxOpts = new AjaxOptions
{
UpdateTargetId = "tableBody"
};
}
<h2>Get User</h2>
<table>
<thead>
<tr>
<th>First</th>
<th>Last</th>
<th>Role</th>
</tr>
</thead>
<tbody id="tableBody">
@Html.Action("GetUserData", new { selectedRole
= Model })
</tbody>
</table>
@using
(Ajax.BeginForm("GetUser", ajaxOpts))
{
<div>
@Html.DropDownList("selectedRole", new SelectList(
new[] { "All"
}.Concat(Enum.GetNames(typeof(Role)))))
<button type="submit">Submit</button>
</div>
}
Output
ADO.net(Active Data Object)
create database dbemp
create table employee(name varchar(50),city varchar(50),address varchar(50))
1. First create database and then
table,then execute create procedure query (below) for inserting values to
employee table.
Create
procedure [dbo].[AddNewEmpDetails]
(
@Name varchar (50),@City varchar
(50),@Address varchar (50)) as begin
Insert into Employee
values(@Name,@City,@Address)
End
AddNewEmpDetails
@Name='Anchu',@City='Trivandram',@Address='East fort'
2. Right click model folder/Add class/name àEmpModel
using
System.ComponentModel.DataAnnotations;
public class EmpModel
{
[Display(Name = "Id")]
public int Empid { get; set; }
[Required(ErrorMessage = "First name is required.")]
public string Name { get; set; }
[Required(ErrorMessage = "City is required.")]
public string City { get; set; }
[Required(ErrorMessage = "Address is required.")]
public string Address { get; set; }
}
}
3. Right click model folder/Add class/name à
EmpRepository
public class EmpRepository
{
private SqlConnection
con;
//To Handle
connection related activities
private void connection()
{
string constr =
ConfigurationManager.ConnectionStrings["getconn"].ToString();
con = new
SqlConnection(constr);
}
//To Add
Employee details
public bool
AddEmployee(EmpModel obj)
{
connection();
SqlCommand com =
new SqlCommand("AddNewEmpDetails", con);
com.CommandType
= CommandType.StoredProcedure;
com.Parameters.AddWithValue("@Name", obj.Name);
com.Parameters.AddWithValue("@City", obj.City);
com.Parameters.AddWithValue("@Address", obj.Address);
con.Open();
int i =
com.ExecuteNonQuery();
con.Close();
if (i >= 1)
{
return true;
}
else
{
return false;
}
}
}
}
4. Right click controller folder/Add
controller/name as Employee1
public class Employee1Controller : Controller
{
// GET: Employee1
public ActionResult
AddEmployee()
{
return View();
}
// POST:
Employee/AddEmployee
[HttpPost]
public ActionResult
AddEmployee(EmpModel Emp)
{
try
{
if
(ModelState.IsValid)
{
EmpRepository EmpRepo = new EmpRepository();
if
(EmpRepo.AddEmployee(Emp))
{
ViewBag.Message = "Employee details added successfully";
}
}
return View();
}
catch
{
return View();
}
}
}
}
5. Right click AddEmployee from
ActionResult,Employee1 controller/Add view/Template to Empty/ModelClass to
EmpModel/Add
@model MVC1.Models.EmpModel
@using
(Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Add Employee</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model
=> model.Name, htmlAttributes: new { @class = "control-label
col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model
=> model.Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model
=> model.Name, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model
=> model.City, htmlAttributes: new { @class = "control-label
col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model
=> model.City, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model
=> model.City, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model
=> model.Address, htmlAttributes: new { @class = "control-label
col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model
=> model.Address, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model
=> model.Address, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2
col-md-10">
<button type="submit" value="Save">Save</button>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2
col-md-10" style="color:green">
@ViewBag.Message
</div>
</div>
</div>
}
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
6. Add connection from server
explorer/Add connection string to web.config.
<configuration>
<connectionStrings>
<add name="getconn" connectionString="Data
Source=TONY;Initial Catalog=dbemp;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
<appSettings>
Output
Scaffolding(CRUD)
ASP.NET
Scaffolding is a code generation framework for ASP.NET Web applications.
CRUD- Create Read Update Delete
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace MVC3.Models
{
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public string
Designation { get; set; }
public string Department { get; set; }
}
public class StudentDBContext:DbContext //database created
{
public DbSet<Student> Students { get; set; }
}
}
2. Add Controller/Select à
MVC5 controller with views using Entity Framework.
output
Data Annotation
DataAnnotations
is used to configure your model classes, which will highlight the most commonly
needed configurations. DataAnnotations are also understood by a number of .NET
applications, such as ASP.NET MVC, which allows these applications to leverage
the same annotations for client-side validations.
System.ComponentModel.DataAnnotations
includes the following attributes that impacts the nullability or size of the
column.
Key
Timestamp
ConcurrencyCheck
Required
MinLength
MaxLength
StringLength
System.ComponentModel.DataAnnotations.Schema
namespace includes the following attributes that impacts the schema of the
database.
Table
Column
Index
ForeignKey
NotMapped
InverseProperty
Key
Entity Framework
Entity
Framework relies on every entity having a key value that it uses for tracking
entities. One of the conventions that Code First depends on is how it implies
which property is the key in each of the Code First classes. Key
Entity
Framework relies on every entity having a key value that it uses for tracking
entities. One of the conventions that Code First depends on is how it implies
which property is the key in each of the Code First classes.
1. Select File/New project/create New
web application/Select Empty/Tick Web API in left side/Create.
2. Tools/NuGet packet manager/Manage new
NuGet packages for solution/check entity installed or not/then install.
Eg:
1. Right click Models from solution
explorer/Add new class Employee
namespace WebApplication39.Models
{
public class Employee
{
public int ID { get; set; }
public string Name { get; set; }
public DateTime
JoiningDate { get; set; }
public int Age { get; set; }
}
}
2. Right click Controller/add
controller/web API/Web API 2 controller-Empty/name as EmployeesController
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebApplication39.Models;
namespace WebApplication39.Controllers
{
public class EmployeesController :
ApiController
{
Employee[] employees
= new Employee[]{
new Employee { ID
= 1, Name = "Mark", JoiningDate =
DateTime.Parse(DateTime.Today.ToString()), Age = 30 },
new Employee { ID
= 2, Name = "Allan", JoiningDate =
DateTime.Parse(DateTime.Today.ToString()), Age = 35 },
new Employee { ID
= 3, Name = "Johny", JoiningDate =
DateTime.Parse(DateTime.Today.ToString()), Age = 21 }
};
public
IEnumerable<Employee> GetAllEmployees()
{
return employees;
}
public
IHttpActionResult GetEmployee(int id)
{
var employee =
employees.FirstOrDefault((p) => p.ID == id);
if (employee == null)
{
return NotFound();
}
return Ok(employee);
}
}
Output
Output with specified Id as 1,2,3 displays corresponding details
MVC Routing(pronounce as rooting)
Routing
is the process of directing an HTTP request to a controller and the
functionality of this processing is implemented in System.Web.Routing.
Click App_Start/RouteConfig.cs/Change defaults:
new { controller = "Calculator"//redirect
to calculator page
public static void
RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller =
"Calculator", action = "Index", id =
UrlParameter.Optional }
);
}
}
Types of Action
Return content
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVC1.Controllers
{
public class ProductController : Controller
{
// GET: Product
public ActionResult
Index()
{
return View();
}
public ActionResult
Search(string name)
{
var input =
Server.HtmlEncode(name);
return
Content(input);
}
}
}
Type address bar as::
https://localhost:44327/Product/search?name=laptop
output
Data Model
1. Right click Model folder/Add name as
EMP
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MVC1.Models
{
public class EMP
{
public int ID { get; set; }
public string Name { get; set; }
public DateTime
JoiningDate { get; set; }
public int Age { get; set; }
}
}
2. Right click Controller folder/select
MVC5 Controller with read/write actions/Add
EMPController as name
3. Delete index() code and paste below
code
public ActionResult Index()
{
var employees = from e in
GetEmployeeList()
orderby e.ID
select e; //LINQ
return
View(employees);
}
4. Paste below code at the end of
controller code
public
List<EMP> GetEmployeeList()
{
return new
List<EMP>{
new EMP{
ID = 1,
Name = "Allan",
JoiningDate =
DateTime.Parse(DateTime.Today.ToString()),
Age = 23
},
new EMP{
ID = 2,
Name = "Carson",
JoiningDate =
DateTime.Parse(DateTime.Today.ToString()),
Age = 45
},
new EMP{
ID = 3,
Name = "Carson",
JoiningDate =
DateTime.Parse(DateTime.Today.ToString()),
Age = 37
},
new EMP{
ID = 4,
Name = "Laura",
JoiningDate =
DateTime.Parse(DateTime.Today.ToString()),
Age = 26
},
};
}
}
}
5. Right click index()/Add Template as
List/Add Model class as EMP/Tick Reference script libraries/then Add/we get
index.cshtml
Ouptut
MVC Helpers
1. @Html.LabelFor
2. @Html.ValidationMessageFor
3. @Html.EditorFor
4. @Html.DisplayNameFor
5. @Html.ActionLink
Page linking using redirection method
namespace
MVC1.Controllers
{
public class RedirectionController : Controller
{
// GET:
Redirection
public ActionResult
Index()
{
return View();
}
public ActionResult
Hello()
{
return
RedirectToAction("Index", "Addition");
}
}
}
Validation
Validation is an important aspect in ASP.NET MVC
applications. It is used to check whether the user input is valid.
Eg:
1. Right
click Model folder/Add class as Student.cs
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace MVCValidation.Models
{
public class Student
{
[Required]
public int StudentId { get; set; }
[Required]
public string StudentName { get; set; }
[Range(10, 20)]
public int Age { get; set; }
}
}
2. Right
click controller/Add controller as Student
public ActionResult
Edit()
{
return View();
}
[HttpPost]
public ActionResult
Edit(Student std)
{
if
(ModelState.IsValid)
{ //checking
model state
//update
student to db
return
RedirectToAction("Index");
}
return View(std);
}
}
}
3. Right click
Edit(),then Add view.
@model MVCValidation.Models.Student
@{
ViewBag.Title = "Edit";
Layout = "~/Views/Shared/_Layout.cshtml"; // we can comment this line for removing
masterpage,Also comment _ViewStart/layout line.
}
<h2>Edit</h2>
@using
(Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Student</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model
=> model.StudentId)
<div class="form-group">
@Html.LabelFor(model
=> model.StudentName, htmlAttributes: new { @class = "control-label
col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model
=> model.StudentName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model
=> model.StudentName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model
=> model.Age, htmlAttributes: new { @class = "control-label
col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model
=> model.Age, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model
=> model.Age, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2
col-md-10">
<input type="submit" value="Save" class="btn
btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to
List", "Index")
</div>
Output
MVC Master page
Master page in MVC is located in
Views/Shared/Layout.cshtml .
We can edit master page.
Output
How to add new
master page
1.
Right
click sharred folder from solution explorer/Add /MVC 5 Layout
page(Razor)/_Layoutpage1/then ok.We get master page.
2.
We can
style master page by copy paste code
from default Master page.
3.
Then
Add new controller/Right click Index()/Tick Use a layout page/Add Masterpage
form Shared folder _LayoutPage1/Add.
Output
CSS
1. Right
click Content folder from solution explorer/Add/Style sheet/Add styles to
StyleSheet1.css.
2. Drag
StyleSheet1.css from solution Explorer and paste in _Layout1(Master Page),we
get this link in master page.
<link href="~/Content/StyleSheet1.css" rel="stylesheet" />
3. We
can run from index page.
Output
Stored Procedure
Eg1:
Create procedure SP as select * from
EmployeeDetails à Execute
SP à Execute
Eg2:
create database dbemp
create table employee(name varchar(50),city varchar(50),address varchar(50))
1.
First
create database and then table,then execute create procedure query (below) for
inserting values to employee table.
Create
procedure [dbo].[AddNewEmpDetails]
(
@Name varchar (50),@City varchar
(50),@Address varchar (50)) as begin
Insert into Employee
values(@Name,@City,@Address)
End
AddNewEmpDetails
@Name='Anchu',@City='Trivandram',@Address='East fort'
No comments:
Post a Comment