1. Trang chủ
  2. » Công Nghệ Thông Tin

ASP.NET 4 Unleased - p 154 ppt

10 45 0

Đang tải... (xem toàn văn)

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 10
Dung lượng 1,05 MB

Nội dung

ptg 1504 NOTE One of the great things about ASP.NET MVC Framework is that it can utilize virtually any ASP.NET facility, including the entire provider model. This enables you to create MVC appli- cations with session state, roles, membership, forms authentication, and much more. The stock project structure includes some prepopulated folders: . Content—Starting point for your site’s content. By default, the Site.css file starts here, and you can add subdirectories for images and other media types. . Controllers—Where all your controllers reside. All controller classes must have a Controller postfix, as shown in Figure 33.3. . Models—A handy starting point for all your web application models. Many enter- prise applications start by deleting this folder and placing the models in a reusable class library. . Scripts—Where all your JavaScript resides. This folder comes prepopulated with a version of jQuery and all the scripts required to support ASP.NET Ajax. . Views—The root of the view folder hierarchy. Below this folder, you can find a fold- er for each controller, named exactly the same as that controller. For example, a Views/Account folder contains all the views used by the AccountController class. CHAPTER 33 Building ASP.NET MVC Applications FIGURE 33.3 Stock ASP.NET MVC 2 project structure in Solution Explorer. From the Library of Wow! eBook ptg 1505 Building an MVC Page 33 Figure 33.3 shows a screenshot of the stock project structure after creating a new ASP.NET MVC project. At this point, because the default project template contains enough scaffolding for you to start, you can press F5 and watch the application run. Note that the application supports forms authentication, new user creation, and user login out-of-the-box. Figure 33.4 shows what it looks like when you run the default ASP.NET MVC project. FIGURE 33.4 Default ASP.NET MVC 2 application. In the next section you create your own MVC page that shows you how MVC’s internal plumbing works. Building an MVC Page This section walks you through the basics of creating a new ASP.NET MVC page. By going through this process you can hopefully get a good feel for how the MVC framework works at a high level. The first thing we to need is a controller. To create a new controller, right-click the Controllers folder in the project created in the previous section, and choose Add and Controller. This brings up a dialog asking you for the controller name and also asks if you want to create stub methods for Create, Update, Delete, and Details. Leave that check box unchecked so we can create our methods manually; call the controller DemoController. When you’re ready, click the Add button. From the Library of Wow! eBook ptg 1506 What you are presented with is an empty MVC controller that looks like the following code: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MvcApplication1.Controllers { public class DemoController : Controller { // // GET: /Demo/ public ActionResult Index() { return View(); } } } Right now, we have a controller called DemoController and a method on that controller called Index. This means that the URLs /demo and /demo/index both work and both execute that method. This is due to the default URL routing configuration. To see the routing configuration in action, open the Global.asax.cs file. If we try to press these URLs, we get an error because no view corresponds to the Index method. The error message that you get from trying to access this URL is so informative to a new MVC developer that we included it as Figure 33.5. In this message you can see how the MVC Framework is attempting to automatically locate a view based on the name of the method invoked and the name of the controller. Now let’s create a view. To do that, create a new folder called Demo under the Views folder. Then, right-click the Demo folder and choose Add; then select View. Here you see several options, including creating a strongly typed view, choosing which type of stock view content should be provided, and the view name. For now, leave all the defaults and name the view Index. This brings up an HTML editing surface for the new view. Note that there is no code- behind for this view—this is by design. If you remember in previous section, separation of concerns tells us that putting a code-behind below a view is a dangerous temptation to start embedding business logic in the view, so code-behinds are left out entirely. If there’s work to be done, it should be done in the controller (fetch and update) or in the model (business logic and data representation). CHAPTER 33 Building ASP.NET MVC Applications From the Library of Wow! eBook ptg 1507 Accepting Form Input 33 Now when you run the application and navigate to the /demo or /demo/index URLs, you should see the default content. As a brief taste of the kind of incredibly powerful functionality you can get from MVC views, add the following line of code somewhere below the word Index in the second content placeholder: <%= Html.ActionLink(“Click here to go home”, “Index”, “Home”) %> This HTML extender actually renders an HTML anchor element. The huge benefit here is that it renders a link to the Index method on the Home controller; the developer doesn’t need to (and shouldn’t!) know about the specific URL. This is just one of dozens of HTML extenders that make creating dynamic views in MVC both powerful and easy. Accepting Form Input Invariably, after seeing a little bit of what MVC is and how it works, developers immedi- ately begin wondering how to invoke server-side events or how to manipulate data and accept input from users. First, you need to remember that in the MVC framework, there is no concept of server-side events. There are no server controls and no concept of postback and invoking server-side events. FIGURE 33.5 Accessing a controller without a corresponding view. From the Library of Wow! eBook ptg 1508 CHAPTER 33 Building ASP.NET MVC Applications So if you don’t have postbacks and server-side events, how do you provide interactivity for your users? To answer this, we have to dust off the corner of our brains that remembers what HTML actually is and unlearn the abstraction layer placed over HTTP by Web Forms. To demonstrate both MVC’s simplicity and power, let’s create a simple form and write a controller method that responds to that form. To start, open the Index.aspx page in the Demo folder and add the following block of code below the Index text: <% using (Html.BeginForm(“DoSomething”, “Demo”, FormMethod.Post)) { %> Enter your favorite color: <%= Html.TextBox(“favoriteColor”, “Blue”) %><br /> <input type=”submit” id=”submit” value=”Submit” /> <% } %> Here we use another HTML extender, the BeginForm method to tell the MVC Framework that we plan to POST the contents of the user-submitted form to whatever URL is mapped to the Demo controller’s DoSomething method. Because we post to the DoSomething method, we should probably create that method in the DemoController class: [HttpPost] public ActionResult DoSomething(string favoriteColor) { ViewData[“color”] = favoriteColor; return View(); } There is an incredibly powerful model binding subsystem that is part of ASP.NET MVC that can take form values and either turn them into method parameters as shown here or even convert them into model classes. For example, if all the form values in a form belong to a Customer class, you can actually pass an instance of the Customer class to the method to which your form posts, and the MVC model binder takes care of mapping everything accordingly. It is a huge timesaver and creates incredibly readable code. Now let’s just create the view. Repeat the process we used last time by right-clicking the Demo folder in the Views folder and add a new view called DoSomething. Put the following markup in the file: <%= ViewData[“color”] %> Now when you request the page at the /demo URL, you are prompted to enter your favorite color. When you do so and click the Submit button, your browser makes an HTTP POST request to /demo/DoSomething, which invokes the code you just added to the DoSomething() method. This sets a variable in the ViewData dictionary. (A facility for providing information from the controller to the view; more can be found on this by From the Library of Wow! eBook ptg 1509 Summary 33 checking out the resources at the end of the chapter.) This variable is then accessed from the DoSomething.aspx view, displaying your favorite color, as shown in Figure 33.6. FIGURE 33.6 Results of posting a form to a Controller method. Summary This chapter provided you with a small taste of what it’s like to build web applications using ASP.NET MVC Framework, which strives for simplicity, ease of maintenance, high testability and reliability, and scalability. If these things interest you and you aren’t a big fan of postback-based development, perhaps you should look into MVC development. This chapter barely scratches the surface of what you can do with ASP.NET MVC Framework but showed you some of the things possible while still being completely compatible with existing ASP.NET functionality such as the provider models, session state, forms authentication, and more. NOTE This chapter barely scratches the surface of ASP.NET MVC Framework and all of the advanced functionality you can leverage from it. For a detailed approach to ASP.NET MVC, read ASP.NET MVC Framework Unleashed from Sams Publishing or check out the official ASP.NET MVC Framework website at http://www.asp.net/mvc. The MVC Framework has historically released new versions faster than Visual Studio, so keep an eye on the official website for the latest version and the publicly available source code if you’re into that sort of thing. From the Library of Wow! eBook ptg This page intentionally left blank From the Library of Wow! eBook ptg CHAPTER 34 Configuring Applications IN THIS CHAPTER . Overview of Website Configuration . Using the Configuration API . Creating Custom Configuration Sections . Creating Encrypted Configuration Sections . Summary In this chapter, you learn how to configure your ASP.NET applications. In the first section, you are provided with an overview of the different sections contained in a web configuration file. You also learn how to modify web configuration files by using both the Web Site Administration Tool and the ASP.NET Microsoft Management Console Snap-In. Next, you learn how to manipulate configuration settings programmatically with the Configuration API. We discuss how you can both retrieve and modify configuration settings. You also learn how to work with configuration settings located at a remote website. You also learn how to add custom configuration sections to the web configuration file. You learn how to register custom configuration sections and interact with custom configura- tion sections with the Configuration API. Finally, we discuss the important topic of protecting your configuration files. You learn how to encrypt different sections of a configuration file so that they cannot be read by human eyes. You also learn how you can deploy an encrypted configuration file from one server to another. Overview of Website Configuration ASP.NET uses a hierarchical system of configuration. At the top of the hierarchy is the Machine.config file. This file contains all the default configuration settings for ASP.NET applications and all other types of applications built with the .NET Framework. From the Library of Wow! eBook ptg 1512 CHAPTER 34 Configuring Applications The Machine.config file is located at the following path: \WINDOWS\Microsoft.NET\Framework\[version]\CONFIG\Machine.config This same folder also contains a Web.config file. The Web.config file contains settings that serve as defaults for all ASP.NET applications running on the machine. The Web.config file overrides particular settings in the Machine.config file. NOTE The \CONFIG folder includes the following six files: . Machine.config—Contains the actual configuration settings. . Machine.config.default—Contains the default values for all configuration settings. . Machine.config.comments—Contains comments on each configuration setting. . Web.config—Contains the actual configuration settings. . Web.config.default—Contains the default values for all configuration settings. . Web.config.comments—Contains comments on each configuration setting. Only the Machine.config and Web.config files are actually used. The other files are for the purpose of documentation. You can place a Web.config file in the root folder of a website, such as the wwwroot folder. A Web.config file located in the root folder of a website contains settings that apply to all applications contained in the website. You also can place a Web.config file in the root of a particular application. In that case, the Web.config file has application scope. Finally, you can place a Web.config file in an application subfolder. In that case, the Web.config file applies to all pages in that folder and below. When an ASP.NET application starts, this hierarchy of configuration files merges and caches in memory. A file dependency is created between the cached configuration settings and the file system. If you make a change to any of the configuration files in the hierar- chy, the new configuration settings are loaded into memory automatically. When an ASP.NET page reads a configuration setting, the setting is read from memory. This means that the ASP.NET Framework can read configuration settings, such as connec- tion strings, efficiently. Furthermore, when you make a change to a configuration setting, you don’t need to stop and restart an application manually for the new setting to take effect. The ASP.NET Framework reloads the cached configuration settings automatically when the configura- tion settings are changed on the file system. (The one exception to this is modifications to the processModel section.) From the Library of Wow! eBook ptg 1513 Overview of Website Configuration WARNING Modifying most configuration settings results in an application restart. Any data stored using the cache or in-process Session state is lost and must be reloaded. You can get around this issue by using external configuration files. See the section “Placing Configuration Settings in an External File” later in this chapter. Additionally, this rarely poses a problem in production environments because developers are typically not mod- ifying these files directly on production servers. The configuration files are XML files. You can modify configuration settings by opening the Machine.config file or a Web.config file and modifying a setting in Notepad. Alternatively, you can change many of the configuration settings (but not all) by using either the Web Site Administration Tool or the ASP.NET Microsoft Management Console Snap-In. Using the Web Site Administration Tool If you use Visual Web Developer (or Visual Studio .NET), you can modify certain configu- ration settings with the Web Site Administration Tool. This tool provides you with a form interface for making configuration changes (see Figure 34.1). 34 FIGURE 34.1 Opening the Web Site Administration Tool. You open the Web Site Administration Tool by selecting Project and then clicking ASP.NET Configuration. Selecting this option opens a browser window that contains the tool. From the Library of Wow! eBook . out-of-the-box. Figure 33 .4 shows what it looks like when you run the default ASP. NET MVC project. FIGURE 33 .4 Default ASP. NET MVC 2 application. In the next section you create your own MVC page. configuration settings for ASP. NET applications and all other types of applications built with the .NET Framework. From the Library of Wow! eBook ptg 1512 CHAPTER 34 Configuring Applications The Machine.config. surface of ASP. NET MVC Framework and all of the advanced functionality you can leverage from it. For a detailed approach to ASP. NET MVC, read ASP. NET MVC Framework Unleashed from Sams Publishing

Ngày đăng: 06/07/2014, 18:20

TÀI LIỆU CÙNG NGƯỜI DÙNG

TÀI LIỆU LIÊN QUAN