Mvc

Furqan Ashraf
Furqan AshrafAssociate Software Engineer em Intelligentsia Software (Pvt) Ltd
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
1 de 51

Recomendados

Asp.net mvc 5 course module 1 overview por
Asp.net mvc 5 course   module 1 overviewAsp.net mvc 5 course   module 1 overview
Asp.net mvc 5 course module 1 overviewSergey Seletsky
2.8K visualizações20 slides
MVC Training Part 1 por
MVC Training Part 1MVC Training Part 1
MVC Training Part 1Lee Englestone
728 visualizações28 slides
ASP.NET MVC Performance por
ASP.NET MVC PerformanceASP.NET MVC Performance
ASP.NET MVC Performancerudib
59.7K visualizações59 slides
Spring MVC por
Spring MVCSpring MVC
Spring MVCAaron Schram
2K visualizações28 slides
Spring mvc por
Spring mvcSpring mvc
Spring mvcHarshit Choudhary
102 visualizações44 slides
Rails review por
Rails reviewRails review
Rails reviewAlan Hecht
925 visualizações19 slides

Mais conteúdo relacionado

Mais procurados

Spring mvc por
Spring mvcSpring mvc
Spring mvcHamid Ghorbani
866 visualizações19 slides
Mvc4 por
Mvc4Mvc4
Mvc4Muhammad Younis
8.5K visualizações282 slides
Discuss About ASP.NET MVC 6 and ASP.NET MVC 5 por
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 5Aaron Jacobson
885 visualizações13 slides
Mvc architecture por
Mvc architectureMvc architecture
Mvc architectureSurbhi Panhalkar
44.5K visualizações28 slides
Spring MVC Architecture Tutorial por
Spring MVC Architecture TutorialSpring MVC Architecture Tutorial
Spring MVC Architecture TutorialJava Success Point
2.3K visualizações7 slides
Spring 3.x - Spring MVC - Advanced topics por
Spring 3.x - Spring MVC - Advanced topicsSpring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topicsGuy Nir
14.4K visualizações35 slides

Mais procurados(20)

Spring mvc por Hamid Ghorbani
Spring mvcSpring mvc
Spring mvc
Hamid Ghorbani866 visualizações
Mvc4 por Muhammad Younis
Mvc4Mvc4
Mvc4
Muhammad Younis8.5K visualizações
Discuss About ASP.NET MVC 6 and ASP.NET MVC 5 por Aaron Jacobson
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
Aaron Jacobson885 visualizações
Mvc architecture por Surbhi Panhalkar
Mvc architectureMvc architecture
Mvc architecture
Surbhi Panhalkar44.5K visualizações
Spring MVC Architecture Tutorial por Java Success Point
Spring MVC Architecture TutorialSpring MVC Architecture Tutorial
Spring MVC Architecture Tutorial
Java Success Point2.3K visualizações
Spring 3.x - Spring MVC - Advanced topics por Guy Nir
Spring 3.x - Spring MVC - Advanced topicsSpring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topics
Guy Nir14.4K visualizações
ASP .net MVC por Divya Sharma
ASP .net MVCASP .net MVC
ASP .net MVC
Divya Sharma5.4K visualizações
Angular - Chapter 1 - Introduction por WebStackAcademy
 Angular - Chapter 1 - Introduction Angular - Chapter 1 - Introduction
Angular - Chapter 1 - Introduction
WebStackAcademy963 visualizações
Spring MVC Basics por Bozhidar Bozhanov
Spring MVC BasicsSpring MVC Basics
Spring MVC Basics
Bozhidar Bozhanov12.4K visualizações
Asp.net mvc presentation by Nitin Sawant por Nitin Sawant
Asp.net mvc presentation by Nitin SawantAsp.net mvc presentation by Nitin Sawant
Asp.net mvc presentation by Nitin Sawant
Nitin Sawant2.3K visualizações
ASP .NET MVC por eldorina
ASP .NET MVC ASP .NET MVC
ASP .NET MVC
eldorina1K visualizações
ASP.NET MVC Presentation por ivpol
ASP.NET MVC PresentationASP.NET MVC Presentation
ASP.NET MVC Presentation
ivpol23.6K visualizações
Angular on ASP.NET MVC 6 por Noam Kfir
Angular on ASP.NET MVC 6Angular on ASP.NET MVC 6
Angular on ASP.NET MVC 6
Noam Kfir2K visualizações
MVC ppt presentation por Bhavin Shah
MVC ppt presentationMVC ppt presentation
MVC ppt presentation
Bhavin Shah14K visualizações
Asp 1a-aspnetmvc por Fajar Baskoro
Asp 1a-aspnetmvcAsp 1a-aspnetmvc
Asp 1a-aspnetmvc
Fajar Baskoro19 visualizações
Asp.Net MVC Intro por Stefano Paluello
Asp.Net MVC IntroAsp.Net MVC Intro
Asp.Net MVC Intro
Stefano Paluello7.9K visualizações
Spring MVC Framework por Hùng Nguyễn Huy
Spring MVC FrameworkSpring MVC Framework
Spring MVC Framework
Hùng Nguyễn Huy3.9K visualizações
Aem best practices por Jitendra Tomar
Aem best practicesAem best practices
Aem best practices
Jitendra Tomar1.6K visualizações

Similar a Mvc

Asp.net With mvc handson por
Asp.net With mvc handsonAsp.net With mvc handson
Asp.net With mvc handsonPrashant Kumar
454 visualizações64 slides
Asp 1-mvc introduction por
Asp 1-mvc introductionAsp 1-mvc introduction
Asp 1-mvc introductionFajar Baskoro
2.1K visualizações40 slides
MVC Framework por
MVC FrameworkMVC Framework
MVC FrameworkAshton Feller
1.4K visualizações27 slides
Asp.net,mvc por
Asp.net,mvcAsp.net,mvc
Asp.net,mvcPrashant Kumar
175 visualizações14 slides
Aspnetmvc 1 por
Aspnetmvc 1Aspnetmvc 1
Aspnetmvc 1Fajar Baskoro
2K visualizações22 slides
MVC 4 por
MVC 4MVC 4
MVC 4Vasilios Kuznos
354 visualizações266 slides

Similar a Mvc(20)

Asp.net With mvc handson por Prashant Kumar
Asp.net With mvc handsonAsp.net With mvc handson
Asp.net With mvc handson
Prashant Kumar454 visualizações
Asp 1-mvc introduction por Fajar Baskoro
Asp 1-mvc introductionAsp 1-mvc introduction
Asp 1-mvc introduction
Fajar Baskoro2.1K visualizações
MVC Framework por Ashton Feller
MVC FrameworkMVC Framework
MVC Framework
Ashton Feller1.4K visualizações
Asp.net,mvc por Prashant Kumar
Asp.net,mvcAsp.net,mvc
Asp.net,mvc
Prashant Kumar175 visualizações
Aspnetmvc 1 por Fajar Baskoro
Aspnetmvc 1Aspnetmvc 1
Aspnetmvc 1
Fajar Baskoro2K visualizações
MVC 4 por Vasilios Kuznos
MVC 4MVC 4
MVC 4
Vasilios Kuznos354 visualizações
Getting started with MVC 5 and Visual Studio 2013 por Thomas Robbins
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
Thomas Robbins14.9K visualizações
Session 1 por Asif Atick
Session 1Session 1
Session 1
Asif Atick521 visualizações
Technoligent providing custom ASP.NET MVC development services por Aaron Jacobson
Technoligent providing custom ASP.NET MVC development servicesTechnoligent providing custom ASP.NET MVC development services
Technoligent providing custom ASP.NET MVC development services
Aaron Jacobson878 visualizações
Simple mvc4 prepared by gigin krishnan por Gigin Krishnan
Simple mvc4 prepared by gigin krishnanSimple mvc4 prepared by gigin krishnan
Simple mvc4 prepared by gigin krishnan
Gigin Krishnan769 visualizações
ASP.Net | Sabin Saleem por SaBin SaleEm
ASP.Net | Sabin SaleemASP.Net | Sabin Saleem
ASP.Net | Sabin Saleem
SaBin SaleEm70 visualizações
Asp.net mvc por Taranjeet Singh
Asp.net mvcAsp.net mvc
Asp.net mvc
Taranjeet Singh248 visualizações
Head first asp.net mvc 2.0 rtt por Lanvige Jiang
Head first asp.net mvc 2.0 rttHead first asp.net mvc 2.0 rtt
Head first asp.net mvc 2.0 rtt
Lanvige Jiang3.6K visualizações
ASP.NET Presentation por Rasel Khan
ASP.NET PresentationASP.NET Presentation
ASP.NET Presentation
Rasel Khan2.5K visualizações
Introduction To Mvc por Volkan Uzun
Introduction To MvcIntroduction To Mvc
Introduction To Mvc
Volkan Uzun2.4K visualizações
Aspnet mvc por Hiep Luong
Aspnet mvcAspnet mvc
Aspnet mvc
Hiep Luong2.2K visualizações
Which is better asp.net mvc vs asp.net por Concetto Labs
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
Concetto Labs27 visualizações
SpringPeople Building Web Sites with ASP.NET MVC FRAMEWORK por SpringPeople
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
SpringPeople7.4K visualizações
ASp.net Mvc 5 por ahmedxp kh
ASp.net Mvc 5ASp.net Mvc 5
ASp.net Mvc 5
ahmedxp kh74 visualizações

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