SlideShare a Scribd company logo
1 of 51
Download to read offline
INTRODUCTION TO MVC
Author: Furqan Ashraf
furqanashraf@ymail.com
What is ASP.NET MVC?
• ASP.NET MVC 4 is a framework for building
scalable, standards-based web applications
using well-established design patterns and
the power of ASP.NET and the .NET
Framework
Why MVC?
• ASP.NET MVC helps to reduce the complexity of the web
application by dividing an application into three layers, Model,
View and Controller.
• This separation (loose coupling) helps in some long term
benefits like isolation of components while development and
also this separation provides better support for test-driven
development (TDD).
• ASP.NET MVC web site are good in performance and also easy
to maintain.
MVC Architecture
• The Model-View-Controller (MVC) pattern is
an architectural design principle that
separates the application components of a
Web application into three layers
The Model
• Model contains and exposes the properties
and application logic In a better way we can
say that The model represents core business
logic and data.
The View
• The View is responsible for creating the
response HTML or any responses back to the
browser like pdf, html or excel etc. In other
way we can say that the view is responsible
for transforming a model or models into a
visual representation.
The Controller
• Controller is responsible for processing user
inputs from view and give responses back to
the view. It means that the controller decides
the action and performs the tasks/logic based
on the parameters. Controller acts as the
coordinator between the view and the model.
Comparing ASP.NET MVC with ASP.NET
Web Forms
• ASP.NET Web form is very rich with server controls but in ASP.NET MVC
there are no server controls supported and its fully depend on HTML
controls.
• There is no View State in ASP.NET MVC. we can use HtmlHelpers in
ASP.NET MVC for rendering HTML controls in a view. ASP.NET MVC is
based on Separation Of Concerns that's why ASP.NET MVC is pluggable
and flexible system. Implementing Test projects with ASP.NET MVC is
simple than Web forms.
• In computer science, separation of concerns (SOC) is a design principle for
separating a computer program into distinct sections, such that each
section addresses a separate concern.
• ASP.NET MVC request cycle is very simpler than Web forms and MVC gives
a good performance. In my opinion I feel for a Web form developer,
ASP.NET MVC is difficult to learn and understand as its much into coding
not much drag and drop but once its fully understood then its very easy.
Comparing ASP.NET MVC with ASP.NET
Web Forms cont.
• Layout page is the Master page available in
ASP.NET MVC and partial views can be
considered as a replacement of user control in
Web form. Web form uses normal Web-
form syntax where as MVC app uses
customizable syntax default to Razor.
Introducing “Razor” – a new view
engine for MVC
• The new view-engine option we’ve been
working on is optimized around HTML
generation using a code-focused templating
approach. The codename for this new view
engine is “Razor”
Razor Design Goals
• Compact, Expressive, and Fluid: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. Razor 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).
Building it with Razor Syntax
• You denote the start of a code block with Razor using a @
character. Unlike <% %> code nuggets, Razor does not
require you to explicitly close the code-block
• Loops and Nested HTML Sample
If-Blocks and Multi-line Statements
• nesting HTML content within an if/else, foreach or other block
statement,
• Layout/MasterPage Scenarios – The Basics
• Layout/MasterPage Scenarios – Adding Section Overrides
Code Based HTML Helpers
• ASP.NET MVC today has the concept of “HTML Helpers” – which are
methods that can be invoked within code-blocks, and which encapsulate
generating HTML. These are implemented using pure code today
(typically as extension methods). All of the existing HTML extension
methods built with ASP.NET MVC (both ones we’ve built and ones built by
others) will work using the “Razor” view engine (no code changes required
Declarative HTML Helpers
• One of the features we are looking to enable
with Razor is an easy way to create re-usable
HTML helpers using a more declarative
approach.
HTML Helpers
• With MVC, HTML helpers are much like traditional ASP.NET Web
Form controls.
• HTML helpers are used to modify HTML. But HTML helpers are
more lightweight.
• HTML helper does not have an event model and a view state.
• In most cases, an HTML helper is just a method that returns a
string.
• Razor Syntax:
• @Html.ActionLink("About this Website", "About")
• ASP Syntax:
• <%=Html.ActionLink("About this Website", "About")%>
• The first parameter is the link text, and the second parameter is the
name of the controller action.
HTML Helpers cont.
• The Html.ActionLink() helper as several properties:
Property Description
.linkText The link text (label)
.actionName The target action
.routeValues The values passed to the
action
.controllerName The target controller
.htmlAttributes The set of attributes to the
link
.protocol The link protocol
.hostname The host name for the link
.fragment The anchor target for the
link
HTML Helpers cont.
• You can pass values to a controller action
• @Html.ActionLink("Edit Record", "Edit", new {Id=3})
• There following HTML helpers can be used to render (modify and output)
HTML form elements:
• BeginForm()
• EndForm()
• TextArea()
• TextBox()
• CheckBox()
• RadioButton()
• ListBox()
• DropDownList()
• Hidden()
• Password()
HTML Helpers cont.
<%= Html.ValidationSummary("Create was
unsuccessful. Please correct the errors and try
again.") %>
<% using (Html.BeginForm()){%>
<p>
<label for="FirstName">First Name:</label>
<%= Html.TextBox("FirstName") %>
<%= Html.ValidationMessage("FirstName", "*")
%>
</p>
<p>
<label for="LastName">Last Name:</label>
<%= Html.TextBox("LastName") %>
<%= Html.ValidationMessage("LastName", "*")
%>
</p>
<p>
<label for="Password">Password:</label>
<%= Html.Password("Password") %>
<%= Html.ValidationMessage("Password", "*")
%>
</p>
<p>
<label for="Password">Confirm
Password:</label>
<%= Html.Password("ConfirmPassword") %>
<%=
Html.ValidationMessage("ConfirmPassword", "*")
%>
</p>
<p>
<label for="Profile">Profile:</label>
<%= Html.TextArea("Profile", new {cols=60,
rows=10})%>
</p>
<p>
<%= Html.CheckBox("ReceiveNewsletter") %>
<label for="ReceiveNewsletter"
style="display:inline">Receive
Newsletter?</label>
</p>
<p>
<input type="submit" value="Register" />
</p>
<%}%>
Passing Inline Templates as Parameters
• One other useful (and extremely powerful) feature we are enabling with Razor is the ability to pass
“inline template” parameters to helper methods. These “inline templates” can contain both HTML
and code, and can be invoked on-demand by helper methods.
The Grid.Render() method call above is C#. We are using the new C#
named parameter syntax to pass strongly-typed arguments to the
Grid.Render method - which means we get full statement
completion/intellisense and compile-time checking for the above syntax.
URL manipulation (URL rewriting)
• URL manipulation, also called URL rewriting, is
the process of altering (often automatically by
means of a program written for that purpose) the
parameters in a URL (Uniform Resource Locator).
• ASP.NET MVC has URL mapping to add custom
routes so any URL can be processed by a
controller.
• routes.MapRoute( "routename",
"products/{id}/{name}/", // URL new {
controller = "MyController", action =
"MyAction"} );
URL manipulation (URL
rewriting)cont.
• Redirect URL to existing file
• If we need to redirect an URL “some_folder/{filename}” to a file in another folder
“another_folder/{filename}”, we can do it using standard method MapPageRoute in the
Global.asax file:
routes.MapPageRoute(“routename”, “some_folder/filename.jpg”,
“~/another_folder/new_filename.jpg”);
• But what if we need to do it for every file in the folder ?
• We can solve this problem using a controller action that will return file contents.
routes.MapRoute( "routename", "some_folder/{filename}.jpg", new { controller = "Home",
action = "RedirectImageFile"} );
• And add the following code to the action method in HomeController.
public class
HomeController : Controller
{ public ActionResult RedirectImageFile(string filename)
{ string url = Url.Content("~/another_folder/"+filename+".jpg"); return base.File(url,
"image/jpeg"); //return base.File(url, "application/octet-stream");
}
}
Working with Entity Framework
• The Entity Framework is a set of technologies in ADO.NET
that support the development of data-oriented software
applications. Architects and developers of data-oriented
applications have struggled with the need to achieve two
very different objectives. They must model the entities,
relationships, and logic of the business problems they are
solving, and they must also work with the data engines
used to store and retrieve the data
• Entity Framework approaches:
1. Database First
2. Model First
3. Code First
Database First
• If you already have a database, the Entity
Framework can automatically generate a data
model that consists of classes and properties that
correspond to existing database objects such as
tables and columns. The information about your
database structure (store schema), your data
model (conceptual model), and the mapping
between them is stored in XML in an .edmx file.
Visual Studio provides the Entity Framework
designer, which is a graphical designer that you
can use to display and edit the .edmx file.
Model First
• If you don't yet have a database, you can
begin by creating a model using the Entity
Framework designer in Visual Studio. When
the model is finished, the designer can
generate DDL (data definition language)
statements to create the database. This
approach also uses an .edmx file to store
model and mapping information
Code First
• Whether you have an existing database or not, you can
code your own classes and properties that correspond
to tables and columns and use them with the Entity
Framework without an .edmx file. That's why you
sometimes see this approach called code only,
although the official name is Code First. The mapping
between the store schema and the conceptual model
represented by your code is handled by convention and
by a special mapping API. If you don't yet have a
database, the Entity Framework can automatically
create the database for you, or drop and re-create it if
the model changes
Code First
1. Create the Application
2. Create the Model
public class Blog
{
public int BlogId { get; set; }
public string Name { get; set; }
public virtual List<Post> Posts { get; set; }
}
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int BlogId { get; set; }
public virtual Blog Blog { get; set; }
}
Code First cont.
• Create a Context
• Add a using statement for System.Data.Entity .
using System.Data.Entity;
Add the following derived context.
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
}
Code First cont.
• Operations.
var name = Console.ReadLine();
var blog = new Blog { Name = name };
db.Blogs.Add(blog);
db.SaveChanges();
// Display all Blogs from the database
var query = from b in db.Blogs
orderby b.Name
select b;
Console.WriteLine("All blogs in the database:");
foreach (var item in query)
{
Console.WriteLine(item.Name);
}
Code First cont.
Code First cont.
• 5. Dealing with Model Changes
The first step is to enable Code First Migrations for our BloggingContext.
Tools -> Library Package Manager -> Package Manager Console
Run the Enable-Migrations command in Package Manager Console
A new Migrations folder has been added to our project that contains two
items:
Configuration.cs – This file contains the settings that Migrations will use for
migrating BloggingContext. We don’t need to change anything for this
walkthrough, but here is where you can specify seed data, register providers for
other databases, changes the namespace that migrations are generated in etc.
<timestamp>_InitialCreate.cs – This is your first migration, it represents the
changes that have already been applied to the database to take it from being an
empty database to one that includes the Blogs and Posts tables.
Code First cont.
public class Blog
{
public int BlogId { get; set; }
public string Name { get; set; }
public string Url { get; set; }
public virtual List<Post> Posts { get; set; }
}
• Run the Add-Migration AddUrl command in Package Manager Console.
The Add-Migration command checks for changes since your last migration
and scaffolds a new migration with any changes that are found. We can
give migrations a name; in this case we are calling the migration ‘AddUrl’.
Database First Approach
• Create a database
• Create a model
• Project -> Add New Item…
• Select Data from the left menu and
then ADO.NET Entity Data Model
Database First Approach cont.
Database First Approach cont.
Database First Approach cont.
Database First Approach cont.
Database First Approach cont.
• Once the reverse engineer process completes the new
model is added to your project and opened up for you
to view in the Entity Framework Designer. An
App.config file has also been added to your project
with the connection details for the database.
• Adding a
controller.
• Right click
controllers
folder
hover to
add then
click
Controller.
• Controller will generate a list of create/edit delete code(LINQ)
automatically.
Adding a view.
• View will be mapped with
the controller.
• You can also add your
costume views.
Introducing NuGet Package
Management for .NET
• NuGet is a package management system for .NET.
The goal of NuGet is to make the process of
incorporating third party libraries into your
solutions as simple as possible.
• There are package managers for operating
systems that install machine-wide libraries, and
there are package managers for developers and
their projects that manage dependencies and
install libraries.
• NuGet takes inspiration from Ruby Gems and
adds some .NET specifics.
• Here's how it works. Notice the "Package Manager Console"
window at the bottom of Visual Studio 2010. That's PowerShell. (It'll
be in View | Other Windows for this release)
• I type List-Package and NuGet goes to a central ATOM feed and
retrieves a list of packages like this (not complete, I snipped it for
the example)
• Id Version Description
-- ------- -----------
Antlr 3.1.1 ANother Tool for Language Rec...
Artem.XmlProviders 2.5 Implementation of XML ASP.NET...
AutoMapper 1.1.0.118 A convention-based object-obj...
Castle.Components.Validator 1.1.0 The Validator component is us...
Castle.Core 1.2.0 Core of the castle project
Castle.DynamicProxy 2.2.0 Castle DynamicProxy is a libr...
Castle.Ioc 2.1.1 Castle Project offers two Inv...
EFCTP4 1.0 This CTP is a an early previe...
elmah 1.1 ELMAH (Error Logging Modules ...
• With NuGet, I type "Install-Package elmah"
and it's done. If I wanted to be extra cool with
PowerShell aliases I could have just typed
"install-packageelmah.“
• PM> Install-Package elmah
Successfully added 'elmah 1.1' to
MvcApplication4
• Looks good. But what if I want to add a more
complex project, maybe NHibernate.Linq.
From the Package Manager Console I'll start
typing install-package nh and get Intellisense
for all the packages that are available.
• Nuget is open source. Hosted at codeplex.
• NuGet is open source and in the Outer curve
Foundation
• NuGet integrates with VS and with PowerShell
• NuGet will have a community managed gallery without
central approving authority
• NuGet won't mess up your computer or install anything
outside your solution
• You can host your own feeds, or read packages out of a
network share/folder
• The whole team - inside and outside Microsoft - really
hopes you like it.
References
• http://weblogs.asp.net/scottgu/archive/2010/07/02/introducing-
razor.aspx
• http://www.codeproject.com/Articles/470107/ASP-NET-MVC-4-
Part-1-Introduction
• http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-
aspnet-mvc4/intro-to-aspnet-mvc-4
• http://msdn.microsoft.com/en-us/library/bb399567.aspx
• http://weblogs.asp.net/scottgu/archive/2010/07/16/code-first-
development-with-entity-framework-4.aspx
• http://msdn.microsoft.com/en-US/data/ee712907
• http://www.w3schools.com/aspnet/mvc_htmlhelpers.asp
• http://maxivak.com/dynamic-url-rewriting-on-asp-net-mvc/
• http://whatis.techtarget.com/definition/URL-manipulation-URL-
rewriting

More Related Content

What's hot

What's hot (20)

Spring mvc
Spring mvcSpring mvc
Spring mvc
 
Mvc4
Mvc4Mvc4
Mvc4
 
Discuss About ASP.NET MVC 6 and ASP.NET MVC 5
Discuss About ASP.NET MVC 6 and ASP.NET MVC 5Discuss About ASP.NET MVC 6 and ASP.NET MVC 5
Discuss About ASP.NET MVC 6 and ASP.NET MVC 5
 
Mvc architecture
Mvc architectureMvc architecture
Mvc architecture
 
Spring MVC Architecture Tutorial
Spring MVC Architecture TutorialSpring MVC Architecture Tutorial
Spring MVC Architecture Tutorial
 
Spring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topicsSpring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topics
 
ASP .net MVC
ASP .net MVCASP .net MVC
ASP .net MVC
 
Angular - Chapter 1 - Introduction
 Angular - Chapter 1 - Introduction Angular - Chapter 1 - Introduction
Angular - Chapter 1 - Introduction
 
Spring MVC Basics
Spring MVC BasicsSpring MVC Basics
Spring MVC Basics
 
Asp.net mvc presentation by Nitin Sawant
Asp.net mvc presentation by Nitin SawantAsp.net mvc presentation by Nitin Sawant
Asp.net mvc presentation by Nitin Sawant
 
ASP .NET MVC
ASP .NET MVC ASP .NET MVC
ASP .NET MVC
 
ASP.NET MVC Presentation
ASP.NET MVC PresentationASP.NET MVC Presentation
ASP.NET MVC Presentation
 
Angular on ASP.NET MVC 6
Angular on ASP.NET MVC 6Angular on ASP.NET MVC 6
Angular on ASP.NET MVC 6
 
MVC ppt presentation
MVC ppt presentationMVC ppt presentation
MVC ppt presentation
 
Asp 1a-aspnetmvc
Asp 1a-aspnetmvcAsp 1a-aspnetmvc
Asp 1a-aspnetmvc
 
Asp.Net MVC Intro
Asp.Net MVC IntroAsp.Net MVC Intro
Asp.Net MVC Intro
 
Spring MVC Framework
Spring MVC FrameworkSpring MVC Framework
Spring MVC Framework
 
Spring aop
Spring aopSpring aop
Spring aop
 
Spring MVC 3.0 Framework
Spring MVC 3.0 FrameworkSpring MVC 3.0 Framework
Spring MVC 3.0 Framework
 
Aem best practices
Aem best practicesAem best practices
Aem best practices
 

Similar to Mvc

Asp.net With mvc handson
Asp.net With mvc handsonAsp.net With mvc handson
Asp.net With mvc handsonPrashant Kumar
 
Asp 1-mvc introduction
Asp 1-mvc introductionAsp 1-mvc introduction
Asp 1-mvc introductionFajar Baskoro
 
Spring MVC framework features and concepts
Spring MVC framework features and conceptsSpring MVC framework features and concepts
Spring MVC framework features and conceptsAsmaShaikh478737
 
Getting started with MVC 5 and Visual Studio 2013
Getting started with MVC 5 and Visual Studio 2013Getting started with MVC 5 and Visual Studio 2013
Getting started with MVC 5 and Visual Studio 2013Thomas Robbins
 
Technoligent providing custom ASP.NET MVC development services
Technoligent providing custom ASP.NET MVC development servicesTechnoligent providing custom ASP.NET MVC development services
Technoligent providing custom ASP.NET MVC development servicesAaron Jacobson
 
Simple mvc4 prepared by gigin krishnan
Simple mvc4 prepared by gigin krishnanSimple mvc4 prepared by gigin krishnan
Simple mvc4 prepared by gigin krishnanGigin Krishnan
 
ASP.Net | Sabin Saleem
ASP.Net | Sabin SaleemASP.Net | Sabin Saleem
ASP.Net | Sabin SaleemSaBin SaleEm
 
Head first asp.net mvc 2.0 rtt
Head first asp.net mvc 2.0 rttHead first asp.net mvc 2.0 rtt
Head first asp.net mvc 2.0 rttLanvige Jiang
 
ASP.NET Presentation
ASP.NET PresentationASP.NET Presentation
ASP.NET PresentationRasel Khan
 
Introduction To Mvc
Introduction To MvcIntroduction To Mvc
Introduction To MvcVolkan Uzun
 
Which is better asp.net mvc vs asp.net
Which is better  asp.net mvc vs asp.netWhich is better  asp.net mvc vs asp.net
Which is better asp.net mvc vs asp.netConcetto Labs
 
SpringPeople Building Web Sites with ASP.NET MVC FRAMEWORK
SpringPeople Building Web Sites with ASP.NET MVC FRAMEWORKSpringPeople Building Web Sites with ASP.NET MVC FRAMEWORK
SpringPeople Building Web Sites with ASP.NET MVC FRAMEWORKSpringPeople
 

Similar to Mvc (20)

Asp.net With mvc handson
Asp.net With mvc handsonAsp.net With mvc handson
Asp.net With mvc handson
 
Asp 1-mvc introduction
Asp 1-mvc introductionAsp 1-mvc introduction
Asp 1-mvc introduction
 
MVC Framework
MVC FrameworkMVC Framework
MVC Framework
 
Asp.net,mvc
Asp.net,mvcAsp.net,mvc
Asp.net,mvc
 
Aspnetmvc 1
Aspnetmvc 1Aspnetmvc 1
Aspnetmvc 1
 
Spring MVC framework features and concepts
Spring MVC framework features and conceptsSpring MVC framework features and concepts
Spring MVC framework features and concepts
 
MVC 4
MVC 4MVC 4
MVC 4
 
Getting started with MVC 5 and Visual Studio 2013
Getting started with MVC 5 and Visual Studio 2013Getting started with MVC 5 and Visual Studio 2013
Getting started with MVC 5 and Visual Studio 2013
 
Session 1
Session 1Session 1
Session 1
 
Technoligent providing custom ASP.NET MVC development services
Technoligent providing custom ASP.NET MVC development servicesTechnoligent providing custom ASP.NET MVC development services
Technoligent providing custom ASP.NET MVC development services
 
Simple mvc4 prepared by gigin krishnan
Simple mvc4 prepared by gigin krishnanSimple mvc4 prepared by gigin krishnan
Simple mvc4 prepared by gigin krishnan
 
ASP.Net | Sabin Saleem
ASP.Net | Sabin SaleemASP.Net | Sabin Saleem
ASP.Net | Sabin Saleem
 
Asp.net mvc
Asp.net mvcAsp.net mvc
Asp.net mvc
 
Head first asp.net mvc 2.0 rtt
Head first asp.net mvc 2.0 rttHead first asp.net mvc 2.0 rtt
Head first asp.net mvc 2.0 rtt
 
ASP.NET Presentation
ASP.NET PresentationASP.NET Presentation
ASP.NET Presentation
 
Introduction To Mvc
Introduction To MvcIntroduction To Mvc
Introduction To Mvc
 
Aspnet mvc
Aspnet mvcAspnet mvc
Aspnet mvc
 
Which is better asp.net mvc vs asp.net
Which is better  asp.net mvc vs asp.netWhich is better  asp.net mvc vs asp.net
Which is better asp.net mvc vs asp.net
 
SpringPeople Building Web Sites with ASP.NET MVC FRAMEWORK
SpringPeople Building Web Sites with ASP.NET MVC FRAMEWORKSpringPeople Building Web Sites with ASP.NET MVC FRAMEWORK
SpringPeople Building Web Sites with ASP.NET MVC FRAMEWORK
 
ASp.net Mvc 5
ASp.net Mvc 5ASp.net Mvc 5
ASp.net Mvc 5
 

Mvc

  • 1. INTRODUCTION TO MVC Author: Furqan Ashraf furqanashraf@ymail.com
  • 2. What is ASP.NET MVC? • ASP.NET MVC 4 is a framework for building scalable, standards-based web applications using well-established design patterns and the power of ASP.NET and the .NET Framework
  • 3. Why MVC? • ASP.NET MVC helps to reduce the complexity of the web application by dividing an application into three layers, Model, View and Controller. • This separation (loose coupling) helps in some long term benefits like isolation of components while development and also this separation provides better support for test-driven development (TDD). • ASP.NET MVC web site are good in performance and also easy to maintain.
  • 4. MVC Architecture • The Model-View-Controller (MVC) pattern is an architectural design principle that separates the application components of a Web application into three layers
  • 5. The Model • Model contains and exposes the properties and application logic In a better way we can say that The model represents core business logic and data.
  • 6. The View • The View is responsible for creating the response HTML or any responses back to the browser like pdf, html or excel etc. In other way we can say that the view is responsible for transforming a model or models into a visual representation.
  • 7. The Controller • Controller is responsible for processing user inputs from view and give responses back to the view. It means that the controller decides the action and performs the tasks/logic based on the parameters. Controller acts as the coordinator between the view and the model.
  • 8. Comparing ASP.NET MVC with ASP.NET Web Forms • ASP.NET Web form is very rich with server controls but in ASP.NET MVC there are no server controls supported and its fully depend on HTML controls. • There is no View State in ASP.NET MVC. we can use HtmlHelpers in ASP.NET MVC for rendering HTML controls in a view. ASP.NET MVC is based on Separation Of Concerns that's why ASP.NET MVC is pluggable and flexible system. Implementing Test projects with ASP.NET MVC is simple than Web forms. • In computer science, separation of concerns (SOC) is a design principle for separating a computer program into distinct sections, such that each section addresses a separate concern. • ASP.NET MVC request cycle is very simpler than Web forms and MVC gives a good performance. In my opinion I feel for a Web form developer, ASP.NET MVC is difficult to learn and understand as its much into coding not much drag and drop but once its fully understood then its very easy.
  • 9. Comparing ASP.NET MVC with ASP.NET Web Forms cont. • Layout page is the Master page available in ASP.NET MVC and partial views can be considered as a replacement of user control in Web form. Web form uses normal Web- form syntax where as MVC app uses customizable syntax default to Razor.
  • 10. Introducing “Razor” – a new view engine for MVC • The new view-engine option we’ve been working on is optimized around HTML generation using a code-focused templating approach. The codename for this new view engine is “Razor”
  • 11. Razor Design Goals • Compact, Expressive, and Fluid: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. Razor 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).
  • 12. Building it with Razor Syntax • You denote the start of a code block with Razor using a @ character. Unlike <% %> code nuggets, Razor does not require you to explicitly close the code-block
  • 13. • Loops and Nested HTML Sample If-Blocks and Multi-line Statements
  • 14. • nesting HTML content within an if/else, foreach or other block statement,
  • 16. • Layout/MasterPage Scenarios – Adding Section Overrides
  • 17. Code Based HTML Helpers • ASP.NET MVC today has the concept of “HTML Helpers” – which are methods that can be invoked within code-blocks, and which encapsulate generating HTML. These are implemented using pure code today (typically as extension methods). All of the existing HTML extension methods built with ASP.NET MVC (both ones we’ve built and ones built by others) will work using the “Razor” view engine (no code changes required
  • 18. Declarative HTML Helpers • One of the features we are looking to enable with Razor is an easy way to create re-usable HTML helpers using a more declarative approach.
  • 19. HTML Helpers • With MVC, HTML helpers are much like traditional ASP.NET Web Form controls. • HTML helpers are used to modify HTML. But HTML helpers are more lightweight. • HTML helper does not have an event model and a view state. • In most cases, an HTML helper is just a method that returns a string. • Razor Syntax: • @Html.ActionLink("About this Website", "About") • ASP Syntax: • <%=Html.ActionLink("About this Website", "About")%> • The first parameter is the link text, and the second parameter is the name of the controller action.
  • 20. HTML Helpers cont. • The Html.ActionLink() helper as several properties: Property Description .linkText The link text (label) .actionName The target action .routeValues The values passed to the action .controllerName The target controller .htmlAttributes The set of attributes to the link .protocol The link protocol .hostname The host name for the link .fragment The anchor target for the link
  • 21. HTML Helpers cont. • You can pass values to a controller action • @Html.ActionLink("Edit Record", "Edit", new {Id=3}) • There following HTML helpers can be used to render (modify and output) HTML form elements: • BeginForm() • EndForm() • TextArea() • TextBox() • CheckBox() • RadioButton() • ListBox() • DropDownList() • Hidden() • Password()
  • 22. HTML Helpers cont. <%= Html.ValidationSummary("Create was unsuccessful. Please correct the errors and try again.") %> <% using (Html.BeginForm()){%> <p> <label for="FirstName">First Name:</label> <%= Html.TextBox("FirstName") %> <%= Html.ValidationMessage("FirstName", "*") %> </p> <p> <label for="LastName">Last Name:</label> <%= Html.TextBox("LastName") %> <%= Html.ValidationMessage("LastName", "*") %> </p> <p> <label for="Password">Password:</label> <%= Html.Password("Password") %> <%= Html.ValidationMessage("Password", "*") %> </p> <p> <label for="Password">Confirm Password:</label> <%= Html.Password("ConfirmPassword") %> <%= Html.ValidationMessage("ConfirmPassword", "*") %> </p> <p> <label for="Profile">Profile:</label> <%= Html.TextArea("Profile", new {cols=60, rows=10})%> </p> <p> <%= Html.CheckBox("ReceiveNewsletter") %> <label for="ReceiveNewsletter" style="display:inline">Receive Newsletter?</label> </p> <p> <input type="submit" value="Register" /> </p> <%}%>
  • 23. Passing Inline Templates as Parameters • One other useful (and extremely powerful) feature we are enabling with Razor is the ability to pass “inline template” parameters to helper methods. These “inline templates” can contain both HTML and code, and can be invoked on-demand by helper methods. The Grid.Render() method call above is C#. We are using the new C# named parameter syntax to pass strongly-typed arguments to the Grid.Render method - which means we get full statement completion/intellisense and compile-time checking for the above syntax.
  • 24. URL manipulation (URL rewriting) • URL manipulation, also called URL rewriting, is the process of altering (often automatically by means of a program written for that purpose) the parameters in a URL (Uniform Resource Locator). • ASP.NET MVC has URL mapping to add custom routes so any URL can be processed by a controller. • routes.MapRoute( "routename", "products/{id}/{name}/", // URL new { controller = "MyController", action = "MyAction"} );
  • 25. URL manipulation (URL rewriting)cont. • Redirect URL to existing file • If we need to redirect an URL “some_folder/{filename}” to a file in another folder “another_folder/{filename}”, we can do it using standard method MapPageRoute in the Global.asax file: routes.MapPageRoute(“routename”, “some_folder/filename.jpg”, “~/another_folder/new_filename.jpg”); • But what if we need to do it for every file in the folder ? • We can solve this problem using a controller action that will return file contents. routes.MapRoute( "routename", "some_folder/{filename}.jpg", new { controller = "Home", action = "RedirectImageFile"} ); • And add the following code to the action method in HomeController. public class HomeController : Controller { public ActionResult RedirectImageFile(string filename) { string url = Url.Content("~/another_folder/"+filename+".jpg"); return base.File(url, "image/jpeg"); //return base.File(url, "application/octet-stream"); } }
  • 26. Working with Entity Framework • The Entity Framework is a set of technologies in ADO.NET that support the development of data-oriented software applications. Architects and developers of data-oriented applications have struggled with the need to achieve two very different objectives. They must model the entities, relationships, and logic of the business problems they are solving, and they must also work with the data engines used to store and retrieve the data • Entity Framework approaches: 1. Database First 2. Model First 3. Code First
  • 27. Database First • If you already have a database, the Entity Framework can automatically generate a data model that consists of classes and properties that correspond to existing database objects such as tables and columns. The information about your database structure (store schema), your data model (conceptual model), and the mapping between them is stored in XML in an .edmx file. Visual Studio provides the Entity Framework designer, which is a graphical designer that you can use to display and edit the .edmx file.
  • 28. Model First • If you don't yet have a database, you can begin by creating a model using the Entity Framework designer in Visual Studio. When the model is finished, the designer can generate DDL (data definition language) statements to create the database. This approach also uses an .edmx file to store model and mapping information
  • 29. Code First • Whether you have an existing database or not, you can code your own classes and properties that correspond to tables and columns and use them with the Entity Framework without an .edmx file. That's why you sometimes see this approach called code only, although the official name is Code First. The mapping between the store schema and the conceptual model represented by your code is handled by convention and by a special mapping API. If you don't yet have a database, the Entity Framework can automatically create the database for you, or drop and re-create it if the model changes
  • 30. Code First 1. Create the Application 2. Create the Model public class Blog { public int BlogId { get; set; } public string Name { get; set; } public virtual List<Post> Posts { get; set; } } public class Post { public int PostId { get; set; } public string Title { get; set; } public string Content { get; set; } public int BlogId { get; set; } public virtual Blog Blog { get; set; } }
  • 31. Code First cont. • Create a Context • Add a using statement for System.Data.Entity . using System.Data.Entity; Add the following derived context. public class BloggingContext : DbContext { public DbSet<Blog> Blogs { get; set; } public DbSet<Post> Posts { get; set; } }
  • 32. Code First cont. • Operations. var name = Console.ReadLine(); var blog = new Blog { Name = name }; db.Blogs.Add(blog); db.SaveChanges(); // Display all Blogs from the database var query = from b in db.Blogs orderby b.Name select b; Console.WriteLine("All blogs in the database:"); foreach (var item in query) { Console.WriteLine(item.Name); }
  • 34. Code First cont. • 5. Dealing with Model Changes The first step is to enable Code First Migrations for our BloggingContext. Tools -> Library Package Manager -> Package Manager Console Run the Enable-Migrations command in Package Manager Console A new Migrations folder has been added to our project that contains two items: Configuration.cs – This file contains the settings that Migrations will use for migrating BloggingContext. We don’t need to change anything for this walkthrough, but here is where you can specify seed data, register providers for other databases, changes the namespace that migrations are generated in etc. <timestamp>_InitialCreate.cs – This is your first migration, it represents the changes that have already been applied to the database to take it from being an empty database to one that includes the Blogs and Posts tables.
  • 35. Code First cont. public class Blog { public int BlogId { get; set; } public string Name { get; set; } public string Url { get; set; } public virtual List<Post> Posts { get; set; } } • Run the Add-Migration AddUrl command in Package Manager Console. The Add-Migration command checks for changes since your last migration and scaffolds a new migration with any changes that are found. We can give migrations a name; in this case we are calling the migration ‘AddUrl’.
  • 36. Database First Approach • Create a database • Create a model • Project -> Add New Item… • Select Data from the left menu and then ADO.NET Entity Data Model
  • 41. Database First Approach cont. • Once the reverse engineer process completes the new model is added to your project and opened up for you to view in the Entity Framework Designer. An App.config file has also been added to your project with the connection details for the database.
  • 42. • Adding a controller. • Right click controllers folder hover to add then click Controller.
  • 43. • Controller will generate a list of create/edit delete code(LINQ) automatically.
  • 44. Adding a view. • View will be mapped with the controller. • You can also add your costume views.
  • 45. Introducing NuGet Package Management for .NET • NuGet is a package management system for .NET. The goal of NuGet is to make the process of incorporating third party libraries into your solutions as simple as possible. • There are package managers for operating systems that install machine-wide libraries, and there are package managers for developers and their projects that manage dependencies and install libraries. • NuGet takes inspiration from Ruby Gems and adds some .NET specifics.
  • 46. • Here's how it works. Notice the "Package Manager Console" window at the bottom of Visual Studio 2010. That's PowerShell. (It'll be in View | Other Windows for this release)
  • 47. • I type List-Package and NuGet goes to a central ATOM feed and retrieves a list of packages like this (not complete, I snipped it for the example) • Id Version Description -- ------- ----------- Antlr 3.1.1 ANother Tool for Language Rec... Artem.XmlProviders 2.5 Implementation of XML ASP.NET... AutoMapper 1.1.0.118 A convention-based object-obj... Castle.Components.Validator 1.1.0 The Validator component is us... Castle.Core 1.2.0 Core of the castle project Castle.DynamicProxy 2.2.0 Castle DynamicProxy is a libr... Castle.Ioc 2.1.1 Castle Project offers two Inv... EFCTP4 1.0 This CTP is a an early previe... elmah 1.1 ELMAH (Error Logging Modules ...
  • 48. • With NuGet, I type "Install-Package elmah" and it's done. If I wanted to be extra cool with PowerShell aliases I could have just typed "install-packageelmah.“ • PM> Install-Package elmah Successfully added 'elmah 1.1' to MvcApplication4
  • 49. • Looks good. But what if I want to add a more complex project, maybe NHibernate.Linq. From the Package Manager Console I'll start typing install-package nh and get Intellisense for all the packages that are available. • Nuget is open source. Hosted at codeplex.
  • 50. • NuGet is open source and in the Outer curve Foundation • NuGet integrates with VS and with PowerShell • NuGet will have a community managed gallery without central approving authority • NuGet won't mess up your computer or install anything outside your solution • You can host your own feeds, or read packages out of a network share/folder • The whole team - inside and outside Microsoft - really hopes you like it.
  • 51. References • http://weblogs.asp.net/scottgu/archive/2010/07/02/introducing- razor.aspx • http://www.codeproject.com/Articles/470107/ASP-NET-MVC-4- Part-1-Introduction • http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with- aspnet-mvc4/intro-to-aspnet-mvc-4 • http://msdn.microsoft.com/en-us/library/bb399567.aspx • http://weblogs.asp.net/scottgu/archive/2010/07/16/code-first- development-with-entity-framework-4.aspx • http://msdn.microsoft.com/en-US/data/ee712907 • http://www.w3schools.com/aspnet/mvc_htmlhelpers.asp • http://maxivak.com/dynamic-url-rewriting-on-asp-net-mvc/ • http://whatis.techtarget.com/definition/URL-manipulation-URL- rewriting