MVC First Basic

19
Asp.Net MVC1 1. Released on Mar 13, 2009 2. Runs on .Net 3.5 and with Visual Studio 2008 & Visual Studio 2008 SP1 3. MVC Pattern architecture with WebForm Engine 4. Html Helpers 5. Ajax helpers 6. Routing 7. Unit Testing Asp.Net MVC2 1. Released on Mar 10, 2010 2. Runs on .Net 3.5, 4.0 and with Visual Studio 2008 & 2010 3. Strongly typed HTML helpers means lambda expression based Html Helpers 4. Templated Helpers 5. Support for Data Annotations Attribute 6. Client-side validation 7. UI helpers with automatic scaffolding & customizable templates 8. Attribute-based model validation on both client and server 9. Overriding the HTTP Method Verb including GET, PUT, POST, and DELETE 10. Areas for partitioning a large applications into modules 11. Asynchronous controllers Asp.Net MVC3 1. Released on Jan 13, 2011 2. Runs on .Net 4.0 and with Visual Studio 2010 3. The Razor view engine 4. Improved Support for Data Annotations 5. Remote Validation 6. Compare Attribute 7. Sessionless Controller 8. Child Action Output Caching 9. Dependency Resolver 10. Entity Framework Code First support

Transcript of MVC First Basic

Asp.Net MVC1

1. Released on Mar 13, 2009

2. Runs on .Net 3.5 and with Visual Studio 2008 & Visual Studio 2008 SP1

3. MVC Pattern architecture with WebForm Engine

4. Html Helpers

5. Ajax helpers

6. Routing

7. Unit Testing

Asp.Net MVC2

1. Released on Mar 10, 2010

2. Runs on .Net 3.5, 4.0 and with Visual Studio 2008 & 2010

3. Strongly typed HTML helpers means lambda expression based Html Helpers

4. Templated Helpers

5. Support for Data Annotations Attribute

6. Client-side validation

7. UI helpers with automatic scaffolding & customizable templates

8. Attribute-based model validation on both client and server

9. Overriding the HTTP Method Verb including GET, PUT, POST, and DELETE

10. Areas for partitioning a large applications into modules

11. Asynchronous controllers

Asp.Net MVC3

1. Released on Jan 13, 2011

2. Runs on .Net 4.0 and with Visual Studio 2010

3. The Razor view engine

4. Improved Support for Data Annotations

5. Remote Validation

6. Compare Attribute

7. Sessionless Controller

8. Child Action Output Caching

9. Dependency Resolver

10. Entity Framework Code First support

11. Partial-page output caching

12. ViewBag dynamic property for passing data from controller to view

13. Global Action Filters

14. Better JavaScript support with unobtrusive JavaScript, jQuery Validation, and JSON binding

15. Use of NuGet to deliver software and manage dependencies throughout the platform

16. Good Intellisense support for Razor into Visual Studio

Asp.Net MVC4

1. Released on Aug 15, 2012

2. Runs on .Net 4.0, 4.5 and with Visual Studio 2010SP1 & Visual Studio 2012

3. ASP.NET Web API

4. Enhancements to default project templates

5. Mobile project template using jQuery Mobile

6. Display Modes

7. Task support for Asynchronous Controllers

8. Bundling and minification

9. Support for the Windows Azure SDK

Asp.Net MVC5 Preview

1. Released on Jun 26, 2013

2. Runs on .Net 4.5, 4.5.1 and with Visual Studio 2013 Preview

3. One Asp.Net

4. Asp.Net Identity

5. ASP.NET Scaffolding

6. Authentication filters - run prior to authorization filters in the ASP.NET MVC pipeline

7. Bootstrap in the MVC template

8. ASP.NET Web API2

1. Model

Models in a MVC based application are the components of the application that are responsible for

maintaining state. Often this state is persisted inside a database for example: we might have a

Product class that is used to represent order data from the Products table inside SQL.

2. View

Views in a MVC based application are the components responsible for displaying the application's

user interface. Typically this UI is created off of the model data for example:

3. Controller

Controllers in a MVC based application are the components responsible for handling end user

interaction, manipulating the model, and ultimately choosing a view to render to display UI. In a

MVC application the view is only about displaying information - it is the controller that handles and

responds to user input and interaction.

Razor View Engine

Web Form View Engine

Razor Engine is an advanced view engine that was introduced with MVC3. This is not a new language but

it is a new markup syntax.

Web Form Engine is the default view engine for the Asp.net MVC that is included with Asp.net MVC from

the beginning.

The namespace for Razor Engine is System.Web.Razor .

The namespace for Webform Engine is System.Web.Mvc.WebFormViewEngine .

The file extensions used with Razor Engine are different from Web Form Engine. It has .cshtml (Razor with

C#) or .vbhtml (Razor with VB) extension for views, partial views, editor templates and for layout pages.

The file extensions used with Web Form Engine are also like Asp.net Web Forms. It has .aspx extension for

views, .ascx extension for partial views & editor templates and .master extension for layout/master pages.

Razor has new and advance syntax that are compact, expressive and reduces typing.

Web Form Engine has the same syntax like Asp.net Web Forms uses for .aspx pages.

Razor syntax are easy to learn and much clean than Web Form syntax. Razor uses @ symbol to make the

code like as:

1. @Html.ActionLink("SignUp", "SignUp")

Web Form syntax are borrowed from Asp.net Web Forms syntax that are mixed with html and sometimes

make a view messy. Webform uses <% and %> delimiters to make the code like as:

1. <%: Html.ActionLink("SignUp", "SignUp") %>

By default, Razor Engine prevents XSS attacks(Cross-Site Scripting Attacks) means it encodes the script or

html tags like <,> before rendering to view.

Web Form Engine does not prevent XSS attacks means any script saved in the database will be fired while

rendering the page

Razor Engine is little bit slow as compared to Webform Engine.

Web Form Engine is faster than Razor Engine.

Razor Engine, doesn't support design mode in visual studio means you cannot see your page look and

feel.

Web Form engine support design mode in visual studio means you can see your page look and feel

without running the application.

Razor Engine support TDD (Test Driven Development) since it is not depend on System.Web.UI.Page class.

Web Form Engine doesn't support TDD (Test Driven Development) since it depend

on System.Web.UI.Page class which makes the testing complex.

// Using the var keyword:

var greeting = "Welcome to W3Schools";

var counter = 103;

var today = DateTime.Today;

// Using data types:

string greeting = "Welcome to W3Schools";

int counter = 103;

DateTime today = DateTime.Today;

@foreach (var x in Request.ServerVariables)

{<li>@x</li>}

@{

string[] members = {"Jani", "Hege", "Kai", "Jim"};

int i = Array.IndexOf(members, "Kai")+1;

intlen = 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>Kai is now in position @i</p>

</body>

</html>

‘@’ is the magic character that precedes code instructions in the following contexts:

‘@’ For a single code line/values:

A single code line inside the markup:

cshtml

<p>

Current time is: @DateTime.Now

</p>

‘@{ … }’ For code blocks with multiple lines:

@{

@:The day is: @DateTime.Now.DayOfWeek. It is a <b>great</b> day!

}

@if(IsPost) {

<p>Hello, the time is @DateTime.Now and this page is a postback!</p>

} else {

<p>Hello, today is: </p> @DateTime.Now

}

<p>Single line If</p>

@if(result != ""){

<p>Result: @result</p>

}

@{

varshowToday = false;

if(showToday){

@DateTime.Today;

} else{

<text>Sorry!</text>

}

}

@{

var weekday=DateTime.Now.DayOfWeek;

var day=weekday.ToString();

var message="";

}

<html>

<body>

@switch(day)

{

case "Monday":

message="This is the first weekday.";

break;

case "Thursday":

message="Only one day before weekend.";

break;

case "Friday":

message="Tomorrow is weekend!";

break;

default:

message="Today is " + day;

break;

}

<p>@message</p>

</body>

</html>

<ul>

@foreach (varmyItem in Request.ServerVariables){

<li>@myItem</li>

}

</ul>

@{

<h3>Team Members</h3>string[] teamMembers = {"Matt", "Joanne", "Robert", "Nancy"};

foreach (var person in teamMembers)

{

<p>@person</p>

}

}

@{

varcountNum = 0;

while (countNum< 50) {

countNum += 1;

<p>Line #@countNum: </p>

}

}

Comments

Comments in Razor are delimited by @**@. If you are inside a C# code block, you can also use // and /*

*/ comment delimiters.

cshtml

@*

A Razor Comment

*@

@{

//A C# comment

/* A Multi

line C# comment

*/

}

Syntax/Sampl

e

Razor Web Forms Equivalent (or

remarks)

Code Block @{

int x = 123;

string y = "because.";

}

<%

int x = 123;

string y = "because.";

%>

Expression

(Html Encoded)

<span>@model.Message</span> <span><%: model.Message

%></span>

Expression

(Unencoded)

<span>

@Html.Raw(model.Message)

</span>

<span><%= model.Message

%></span>

Combining Text

and markup

@foreach(var item in items) {

<span>@item.Prop</span>

}

<% foreach(var item in

items) { %>

<span><%: item.Prop

%></span>

<% } %>

Mixing code and

Plain text

@if (foo) {

<text>Plain Text</text>

}

<% if (foo) { %>

Plain Text

<% } %>

Mixing code and

plain text

(alternate)

@if (foo) {

@:Plain Text is @bar

}

Same as above

Email Addresses Hi [email protected] Razor recognizes basic email

format and is smart enough not to

treat the @ as a code delimiter

Explicit

Expression

<span>ISBN@(isbnNumber)</span

>

In this case, we need to be explicit

about the expression by using

parentheses.

Escaping the @

sign

<span>In Razor, you use the

@@foo to display the value

of foo</span>

@@ renders a single @ in the

response.

Server side

Comment

@*

This is a server side

<%--

This is a server side

multiline comment

*@

multiline comment

--%>

Calling generic

method

@(MyClass.MyMethod<AType>()) Use parentheses to be explicit

about what the expression is.

Creating a

Razor Delegate

@{

Func<dynamic, object> b =

@<strong>@item</strong>;

}

@b("Bold this")

Generates a Func<T,

HelperResult> that you can call

from within Razor. See this blog

postfor more details.

Mixing

expressions and

text

Hello @title. @name. Hello <%: title %>. <%:

name %>.

NEW IN RAZOR v2.0/ASP.NET MVC 4

Conditional

attributes

<div

class="@className"></div>

When className = null

<div></div>

When className = ""

<div class=""></div>

When className = "my-class"

<div class="my-

class"></div>

Conditional

attributes with

other literal

values

<div class="@className foo

bar">

</div>

When className = null

<div class="foo

bar"></div>

Notice the leading space in front

of foo is removed.

When className = "my-class"

<div class="my-class foo

bar">

</div>

Conditional

data-*

attributes.

data-*

attributes are

always

rendered.

<div data-x="@xpos"></div> When xpos = null or ""

<div data-x=""></div>

When xpos = "42"

<div data-x="42"></div>

Boolean <input type="checkbox" When isChecked = true

attributes checked="@isChecked" /> <input type="checkbox"

checked="checked" />

When isChecked = false

<input type="checkbox"

/>

URL Resolution

with tilde

<script src="~/myscript.js">

</script>

When the app is at /

<script

src="/myscript.js">

</script>

When running in a virtual

application namedMyApp

<script

src="/MyApp/myscript.js"

>

</script>

Operator Description Examples

+

-

*

/

Math operators used in numerical

expressions.

@(5 + 13)

@{ varnetWorth = 150000; }

@{ varnewTotal = netWorth * 2; }

@(newTotal / 2)

=

Assignment. Assigns the value on the right

side of a statement to the object on the

left side. var age = 17;

==

Equality. Returns true if the values are

equal. (Notice the distinction between

the =operator and the ==operator.)

varmyNum = 15;

if (myNum == 15) {

// Do something.

}

!=

Inequality. Returns true if the values are

not equal.

vartheNum = 13;

if (theNum != 15) {

// Do something.

}

<

>

<=

>=

Less-than,

greater-than,

less-than-or-equal, and

greater-than-or-equal.

if (2<3) {

// Do something.

}

varcurrentCount = 12;

if(currentCount>= 12) {

// Do something.

}

+

Concatenation, which is used to join

strings. ASP.NET knows the difference

between this operator and the addition

operator based on the data type of the

expression.

// The displayed result is

"abcdef".

@("abc" + "def")

+=

-=

The increment and decrement operators,

which add and subtract 1 (respectively)

from a variable. inttheCount = 0;

theCount += 1; // Adds 1 to count

.

Dot. Used to distinguish objects and their

properties and methods.

varmyUrl = Request.Url;

var count =

Request["Count"].AsInt();

()

Parentheses. Used to group expressions

and to pass parameters to methods. @(3 + 7)

@Request.MapPath(Request.FilePath);

[]

Brackets. Used for accessing values in

arrays or collections. var income =

Request["AnnualIncome"];

!

Not. Reverses a true value to false and

vice versa. Typically used as a shorthand

way to test forfalse (that is, for

not true).

booltaskCompleted = false;

// Processing.

if(!taskCompleted) {

// Continue processing

}

&& Logical AND and OR, which are used to boolmyTaskCompleted = false;

|| link conditions together. inttotalCount = 0;

// Processing.

if(!myTaskCompleted&&totalCount<12)

{

// Continue processing.

}

Compact, Expressive, and Fluid: Razor minimizes the number of characters and keystrokes required in a file, and enables a fast, fluid coding workflow. Unlike most template syntaxes, you do not need to interrupt your coding to explicitly denote server blocks within your HTML. The parser is smart enough to infer this from your code. This enables a really compact and expressive syntax which is clean, fast and fun to type.

Easy to Learn: Razor is easy to learn and enables you to quickly be productive with a minimum of concepts. You use all your existing language and HTML skills.

Is not a new language: We consciously chose not to create a new imperative language with Razor. Instead we wanted to enable developers to use their existing C#/VB (or other) language skills with Razor, and deliver a template markup syntax that enables an awesome HTML construction workflow with your language of choice.

Works with any Text Editor: Razor doesn’t require a specific tool and enables you to be productive in any plain old text editor (notepad works great).

Has great Intellisense: While Razor has been designed to not require a specific tool or code editor, it will have awesome statement completion support within Visual Studio. We’ll be updating Visual Studio 2010 and Visual Web Developer 2010 to have full editor intellisense for it.

Unit Testable: The new view engine implementation will support the ability to unit test views (without requiring a controller or web-server, and can be hosted in any unit test project – no special app-domain required).

Similarities between ViewBag&ViewData :

Helps to maintain data when you move from controller to view.

Used to pass data from controller to corresponding view.

Short life means value becomes null when redirection occurs. This is because their goal is to provide a

way to communicate between controllers and views. It’s a communication mechanism within the server

call.

Difference between ViewBag&ViewData:

ViewData is a dictionary of objects that is derived from ViewDataDictionary class and accessible using

strings as keys.

ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.

ViewData requires typecasting for complex data type and check for null values to avoid error.

ViewBag doesn’t require typecasting for complex data type.

ViewBag&ViewData Example:

publicActionResult Index()

{

ViewBag.Name = "MonjurulHabib";

return View();

}

publicActionResult Index()

{

ViewData["Name"] = "MonjurulHabib";

return View();

}

In View:

@ViewBag.Name

@ViewData["Name"]

empData:

TempData is also a dictionary derived from TempDataDictionary class and stored in short lives session

and it is a string key and object value. The difference is that the life cycle of the object. TempData keep

the information for the time of an HTTP Request. This mean only from one page to another. This also

work with a 302/303 redirection because it’s in the same HTTP Request. Helps to maintain data when

you move from one controller to other controller or from one action to other action. In other words

when you redirect, “Tempdata” helps to maintain data between those redirects. It internally uses

session variables. Temp data use during the current and subsequent request only means it is use when

you are sure that next request will be redirecting to next view. It requires typecasting for complex data

type and check for null values to avoid error. generally used to store only one time messages like error

messages, validation messages.

publicActionResult Index()

{

var model = new Review()

{

Body = "Start",

Rating=5

};

TempData["ModelName"] = model;

returnRedirectToAction("About");

}

<pre><pre lang="cs">public ActionResult About()

{

var model= TempData["ModelName"];

return View(model);

}

The Temodata mechanism is the Session which work like the ViewData, like a Dictionary that take a

string for key and object for value. This one is stored into the client Cookie and can be used for a much

more long time. It also need more verification to never have any confidential information. Regarding

ViewData or ViewBag you should use it intelligently for application performance. Because each action

goes through the whole life cycle of regular asp.net mvc request. You can use ViewData/ViewBag in your

child action but be careful that you are not using it to populate the unrelated data which can pollute

your controller.

The App_Data Folder

The App_Data folder is for storing application data.

We will add an SQL database to the App_Data folder, later in this tutorial.

The Content Folder

The Content folder is used for static files like style sheets (css files), icons and images.

Visual Web Developer automatically adds a themes folder to the Content folder. The

themes folder is filled with jQuery styles and pictures. In this project you can delete the themes folder.

Visual Web Developer also adds a standard style sheet file to the project: the

file Site.css in the content folder. The style sheet file is the file to edit when you want to change the style of the application.

We will edit the style sheet file (Site.css) file in the next chapter of this tutorial.

The Controllers Folder

The Controllers folder contains the controller classes responsible for handling user input and

responses.

MVC requires the name of all controller files to end with "Controller".

Visual Web Developer has created a Home controller (for the Home and the About page) and an Account controller (for Login pages):

We will create more controllers later in this tutorial.

The Models Folder

The Models folder contains the classes that represent the application models. Models hold and manipulate application data.

We will create models (classes) in a later chapter of this tutorial.

The Views Folder

The Views folder stores the HTML files related to the display of the application (the user

interfaces).

The Views folder contains one folder for each controller.

Visual Web Developer has created an Account folder, a Home folder, and a Shared folder (inside the Views folder).

The Account folder contains pages for registering and logging in to user accounts.

The Home folder is used for storing application pages like the home page and the about page.

The Shared folder is used to store views shared between controllers (master pages and layout pages).

We will edit the layout files in the next chapter of this tutorial.

The Scripts Folder

The Scripts folder stores the JavaScript files of the application.

By default Visual Web Developer fills this folder with standard MVC, Ajax, and jQuery files:

Note: The files named "modernizr" are JavaScript files used for supporting HTML5 and CSS3 features in the application.