ASP.NET MVC 3

advertisement
ASP.NET MVC 3
ASP.Net MVC Overview:
The Model-View-Controller (MVC) architectural pattern separates an application into three
main components: the model, the view, and the controller. The ASP.NET MVC framework
provides an alternative to the ASP.NET Web Forms pattern for creating MVC-based Web
applications. The MVC framework is defined in the System.Web.Mvc namespace and is a
fundamental, supported part of the System.Web namespace. MVC is a standard design pattern
that many developers are familiar with. Some types of Web applications will benefit from the
MVC framework. Others will continue to use the traditional ASP.NET application pattern that
is based on Web Forms and postbacks. Other types of Web applications will combine the two
approaches;
neither approach
excludes the other.
Models. Model objects are the parts of the application that implement the logic for the
application s data domain. Often, model objects retrieve and store model state in a database.
For example, a Product object might retrieve information from a database, operate on it, and
then write updated information back to a Products table in SQL Server.
Views. Views are the components that display the application s user interface (UI). Typically,
this UI is created from the model data. An example would be an edit view of a Products table
that displays text boxes, drop-down lists, and check boxes based on the current state of a
Products object.
Controllers. Controllers are the components that handle user interaction, work with the
model, and ultimately select a view to render that displays UI. In an MVC application, the
view only displays information; the controller handles and responds to user input and
interaction. For example, the controller handles query-string values, and passes these values to
the model, which in turn queries the database by using the values.
The loose coupling between the three main components of an MVC application also promotes
parallel development. For instance, one developer can work on the view, a second developer
can work on the controller logic, and a third developer can focus on the business logic in the
model.
Deciding When to Create an MVC Application
Before you decide to use the MVC framework or the Web Forms model for a specific Web
site, weigh the advantages of each approach.
Advantages of an MVC-Based Web Application
The ASP.NET MVC framework offers the following advantages:





It makes it easier to manage complexity by dividing an application into the model, the
view, and the controller.
It does not use view state or server-based forms. This makes the MVC framework ideal
for developers who want full control over the behavior of an application.
It uses a Front Controller pattern that processes Web application requests through a
single controller. This enables you to design an application that supports a rich routing
infrastructure. For more information, see Front Controller on the MSDN Web site.
It provides better support for test-driven development (TDD).
It works well for Web applications that are supported by large teams of developers and
Web designers who need a high degree of control over the application behavior.
Advantages of a Web Forms-Based Web Application
The Web Forms-based framework offers the following advantages:





It supports an event model that preserves state over HTTP, which benefits line-ofbusiness Web application development. The Web Forms-based application provides
dozens of events that are supported in hundreds of server controls.
It uses a Page Controller pattern that adds functionality to individual pages. For more
information, see Page Controller on the MSDN Web site.
It uses view state or server-based forms, which can make managing state information
easier.
It works well for small teams of Web developers and designers who want to take
advantage of the large number of components available for rapid application
development.
In general, it is less complex for application development, because the components (the
Page class, controls, and so on) are tightly integrated and usually require less code than
the MVC model.
Features of the ASP.NET MVC Framework
The ASP.NET MVC framework provides the following features:
 Separation of application tasks (input logic, business logic, and UI logic), testability,
and test-driven development (TDD) by default.
 An extensible and pluggable framework. The components of the ASP.NET MVC
framework are designed so that they can be easily replaced or customized.
 A powerful URL-mapping component that lets you build applications that have
comprehensible and searchable URLs.
 Support for using the markup in existing ASP.NET page (.aspx files), user control
(.ascx files), and master page (.master files) markup files as view templates. You can
use existing ASP.NET features with the ASP.NET MVC framework, such as nested
master pages, in-line expressions (<%= %>), declarative server controls, templates,
data-binding, localization, and so on.
 Support for existing ASP.NET features. ASP.NET MVC lets you use features such as
forms authentication and Windows authentication, URL authorization, membership and
roles, output and data caching, session and profile state management, health
monitoring, the configuration system, and the provider architecture.
Understanding the ASP.NET MVC Execution Process
Requests to an ASP.NET MVC-based Web application first pass through the
UrlRoutingModule object, which is an HTTP module. This module parses the request and
performs route selection. The UrlRoutingModule object selects the first route object that
matches the current request. (A route object is a class that implements RouteBase, and is
typically an instance of the Route class.) If no routes match, the UrlRoutingModule object
does nothing and lets the request fall back to the regular ASP.NET or IIS request processing.
From the selected Route object, the UrlRoutingModule object obtains the IRouteHandler
object that is associated with the Route object. Typically, in an MVC application, this will be
an instance of MvcRouteHandler. The IRouteHandler instance creates an IHttpHandler
object and passes it the IHttpContext object. By default, the IHttpHandler instance for
MVC is the MvcHandler object. The MvcHandler object then selects the controller that will
ultimately handle the request.
When an ASP.NET MVC Web application runs in IIS 7.0, no file name extension is required
for MVC projects. However, in IIS 6.0, the handler requires that you map the .mvc file name
extension to the ASP.NET ISAPI DLL.
The module and handler are the entry points to the ASP.NET MVC framework. They perform
the following actions:



Select the appropriate controller in an MVC Web application.
Obtain a specific controller instance.
Call the controller s Execute method.
The following table lists the stages of execution for an MVC Web project.
Understanding Models, Views, and Controllers (C#)
A URL Does Not Equal a Page
When you build a traditional ASP.NET Web Forms application or an Active Server Pages
application, there is a one-to-one correspondence between a URL and a page. If you request a
page named SomePage.aspx from the server, then there had better be a page on disk named
SomePage.aspx. If the SomePage.aspx file does not exist, you get an ugly 404 - Page Not
Found error.
When building an ASP.NET MVC application, in contrast, there is no correspondence
between the URL that you type into your browser's address bar and the files that you find in
your application. In an ASP.NET MVC application, a URL corresponds to a controller action
instead of a page on disk.
In a traditional ASP.NET or ASP application, browser requests are mapped to pages. In an
ASP.NET MVC application, in contrast, browser requests are mapped to controller actions.
An ASP.NET Web Forms application is content-centric. An ASP.NET MVC application, in
contrast, is application logic centric.
Understanding ASP.NET Routing
A browser request gets mapped to a controller action through a feature of the ASP.NET
framework called ASP.NET Routing. ASP.NET Routing is used by the ASP.NET MVC
framework to route incoming requests to controller actions.
ASP.NET Routing uses a route table to handle incoming requests. This route table is created
when your web application first starts. The route table is setup in the Global.asax file.
using
using
using
using
using
using
System;
System.Collections.Generic;
System.Linq;
System.Web;
System.Web.Mvc;
System.Web.Routing;
namespace MvcApplication1
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default",
// Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" }//Parameter
defaults
);
}
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
}
}
}
When an ASP.NET application first starts, the Application_Start() method is called. This method calls
the RegisterRoutes() method and the RegisterRoutes() method creates the default route table.
The default route table consists of one route. This default route breaks all incoming requests into three
segments (a URL segment is anything between forward slashes). The first segment is mapped to a
controller name, the second segment is mapped to an action name, and the final segment is mapped to
a parameter passed to the action named Id
For example, consider the following URL:
/Product/Details/3
This URL is parsed into three parameters like this:
Controller = Product
Action = Details
Id = 3
The Default route defined in the Global.asax file includes default values for all three parameters. The
default Controller is Home, the default Action is Index, and the default Id is an empty string. With
these defaults in mind, consider how the following URL is parsed:
/Employee
This URL is parsed into three parameters like this:
Controller = Employee
Action = Index
Id = ��
Finally, if you open an ASP.NET MVC Application without supplying any URL (for example,
http://localhost) then the URL is parsed like this:
Controller = Home
Action = Index
Id = ��
The request is routed to the Index() action on the HomeController class.
Understanding Controllers
A controller is responsible for controlling the way that a user interacts with an MVC application. A
controller contains the flow control logic for an ASP.NET MVC application. A controller determines
what response to send back to a user when a user makes a browser request.A controller is just a class
(for example, a Visual Basic or C# class).
The sample ASP.NET MVC application includes a controller named HomeController.cs located in the
Controllers folder.
using
using
using
using
using
System;
System.Collections.Generic;
System.Linq;
System.Web;
System.Web.Mvc;
namespace MvcApplication1.Controllers
{
[HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
ViewData["Title"] = "Home Page";
ViewData["Message"] = "Welcome to ASP.NET MVC!";
return View();
}
public ActionResult About()
{
ViewData["Title"] = "About Page";
return View();
}
}
}
Notice that the HomeController has two methods named Index() and About(). These two methods
correspond to the two actions exposed by the controller. The URL /Home/Index invokes the
HomeController.Index() method and the URL /Home/About invokes the HomeController.About()
method.
Any public method in a controller is exposed as a controller action. You need to be careful about this.
This means that any public method contained in a controller can be invoked by anyone with access to
the Internet by entering the right URL into a browser.
You can put some parameters in the controller action. It means that you will extend the URL for more
parameter. For instance, the Url ‘/HelloWorld/Welcome?name=xxx&numtimes=4’ will translate into:
the ‘HelloWorldController’ controller class, Welcome(string name, int numtimes) action. We can use
the URL like ‘/HelloWorld/Welcome/dat/3’ by config the RegisterRoutes(…) function on the
Global.asax.cs file like :
routes.MapRoute(
"HelloRoute", // Route name
"{controller}/{action}/{name}/{numtimes}", // URL with parameters
new { controller = "HelloWorld", action = "Index", name =
UrlParameter.Optional, numtimes = UrlParameter.Optional } // Parameter defaults
);
Both cases will call the same controller and action name.
Understanding Views
The two controller actions exposed by the HomeController class, Index() and About(), both return a
view. A view contains the HTML markup and content that is sent to the browser. A view is the
equivalent of a page when working with an ASP.NET MVC application.
You must create your views in the right location. The HomeController.Index() action returns a view
located at the following path:
\Views\Home\Index.aspx
The HomeController.About() action returns a view located at the following path:
\Views\Home\About.aspx
In general, if you want to return a view for a controller action, then you need to create a subfolder in
the Views folder with the same name as your controller. Within the subfolder, you must create an
.aspx file with the same name as the controller action.
the About.aspx view.
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage" %>
<asp:Content ID="aboutContent" ContentPlaceHolderID="MainContent" runat="server">
<h2>About</h2>
<p>
Put content here.
</p>
</asp:Content>
Understanding Models
An MVC model contains all of your application logic that is not contained in a view or a controller.
The model should contain all of your application business logic, validation logic, and database access
logic
A view should contain only logic related to generating the user interface. A controller should only
contain the bare minimum of logic required to return the right view or redirect the user to another
action (flow control). Everything else should be contained in the model.
Note:
Adding Model: In Solution Explorer, right-click the Models folder, select Add, and then click Class.
Adding View: Right click on the ‘Action’ name and click add view choose some parameter and click Add
button.
You can set layout for template directly on template page. You do not set, it automatically get the layout on
_ViewStart.cshtml file.
From Controller, you can use this.ViewBag or this.ViewData to transfer data from controller to view. Both of
them have the same way, however in MVC3 it use ViewBag as the new feature.
For example:
public ActionResult Index()
{
List<string> colors = new List<string>();
colors.Add("red");
colors.Add("green");
colors.Add("blue");
ViewData["listColors"] = colors;
ViewData["dateNow"] = DateTime.Now;
ViewData["name"] = "Hajan";
ViewData["age"] = 25;
return View();
}
View (ASPX View Engine)
<p>
My name is
<b><%: ViewData["name"] %></b>,
<b><%: ViewData["age"] %></b> years old.
<br />
I like the following colors:
</p>
<ul id="colors">
<% foreach (var color in ViewData["listColors"] as List<string>){ %>
<li>
<font color="<%: color %>"><%: color %></font>
</li>
<% } %>
</ul>
<p>
<%: ViewData["dateNow"] %>
public ActionResult Index()
{
List<string> colors = new List<string>();
colors.Add("red");
colors.Add("green");
colors.Add("blue");
ViewBag.ListColors = colors; //colors is List
ViewBag.DateNow = DateTime.Now;
ViewBag.Name = "Hajan";
ViewBag.Age = 25;
return View();
}
View (ASPX View Engine)
<p>
My name is
<b><%: ViewBag.Name %></b>,
<b><%: ViewBag.Age %></b> years old.
<br />
I like the following colors:
</p>
<ul id="colors">
<% foreach (var color in ViewBag.ListColors) { %>
<li>
<font color="<%: color %>"><%: color %></font>
</li>
<% } %>
</ul>
<p>
<%: ViewBag.DateNow %>
</p>
Some method of Html object:






The ActionLink method of the helper makes it easy to dynamically generate HTML hyperlinks
that link to action methods on controllers. The first argument to the ActionLink method is the
link text to render (for example, <a>Edit Me</a>). The second argument is the name of the
action method to invoke. The final argument is an anonymous object that generates the route
data (in this case, the ID of 4).
The Html.LabelFor helper displays the name of the field ("Title", "ReleaseDate", "Genre", or
"Price").
The Html.EditorFor helper displays an HTML <input> element.
The Html.ValidationMessageFor helper displays any validation messages associated with that
property.
Html.BeginForm(…) include the form tag.
Enabling Client-Side Validation
To enable client-side validation in ASP.NET MVC 3, you must set two flags and you must include
three JavaScript files.
Open the application's Web.config file. Verify ClientValidationEnabled and UnobtrusiveJavaScriptEnabled
are set to true in the application settings. The following fragment from the root Web.config file shows
the correct settings:
<appSettings>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
You also need to include several JavaScript files in the rendered view. An easy way to include the
JavaScript in all views is to add them to the Views\Shared\_Layout.cshtml file. Replace the <head>
element of the _Layout.cshtml file with the following code:
<head>
<title>@View.Title</title>
<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css"
/>
<script src="http://ajax.microsoft.com/ajax/jQuery/jquery1.4.2.min.js"></script>
<script
src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></
script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"
type="text/javascript"></script>
</head>
Strongly Typed Models and the @model Keyword
Earlier in this tutorial, you saw how a controller can pass data or objects to a view template using the
ViewBag object. The ViewBag is a dynamic object that provides a convenient late-bound way to pass
information to a view.
ASP.NET MVC also provides the ability to pass strongly typed data or objects to a view template.
This strongly typed approach enables better compile-time checking of your code and richer
IntelliSense in the Visual Web Developer editor.
Notice how the code creates a List object when it calls the View helper method in the Index action
method. The code then passes this Movies list from the controller to the view:
public ViewResult Index()
{
return View(db.Movies.ToList());
}
By including a @model statement at the top of the view template file, you can specify the type of
object that the view expects. When you created the movie controller, Visual Web Developer
automatically included the following @model statement at the top of the Index.cshtml file:
@model IEnumerable<MvcMovie.Models.Movie>
This @model directive allows you to access the list of movies that the controller passed to the view by
using a Model object that's strongly typed.
Some methods on Controller class



RedirectToAction(…): redirect to specified action on current controller using action name
HttpNotFound(…):Returns an instance of the HttpNotFoundResult class.
Download