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

ASP.NET 4.0 in Practice phần 4 pps

50 388 0

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

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 50
Dung lượng 15,35 MB

Nội dung

125TECHNIQUE 32 The first application private static MetaModel s_defaultModel = new MetaModel(); public static MetaModel DefaultModel { get { return s_defaultModel; } } public static void RegisterRoutes(RouteCollection routes) { ContextConfiguration config = new ContextConfiguration() { ScaffoldAllTables = true }; DefaultModel.RegisterContext(typeof(NorthwindEntities), config); } } VB: Public Class [Global] Inherits System.Web.HttpApplication Private Shared s_defaultModel As New MetaModel() Public Shared ReadOnly Property DefaultModel() As MetaModel Get Return s_defaultModel End Get End Property Public Shared Sub RegisterRoutes(ByVal routes As RouteCollection) Dim config As New ContextConfiguration() config.ScaffoldAllTables = True DefaultModel.RegisterContext( GetType(NorthwindEntities), config) End Sub End Class In this example, we’re using Entity Framework, but with LINQ to SQL both the code and the concepts are identical. The ScaffoldAllTables property is important because by default its value is false . By setting it to true , you’ll automatically show all the tables in the first page. When you create a new application based on this project, you’ll notice that all the code is already in place, and you don’t need to write it! A new route is also registered: C#: routes.Add(new DynamicDataRoute ("{table}/{action}.aspx") { Constraints = new RouteValueDictionary(new { action = "List|Details|Edit|Insert" }), Model = DefaultModel }); VB: routes.Add(New DynamicDataRoute("{table}/{action}.aspx") With { .Constraints = New RouteValueDictionary(New With { Shows all tables ObjectContext 126 CHAPTER 5 Data binding in ASP.NET Web Forms .Action = "List|Details|Edit|Insert"}), .Model = DefaultModel }) Dynamic Data controls work with a friendly URL, such as /Products/List.aspx. You can change the generated URL to reflect your needs. You can protect these URLs using standard authorization and authentication features from ASP.NET, such as UrlAutho- rization and FormsAuthentication . When you’re running the project, you’ll receive a list of tables, shown in figure 5.12. If you navigate to each table, you can see how the controls perform in different sit- uations, such as filtering, paging, or inserting. From a technical point of view, the page templates are defined under the Dynamic- Data/PageTemplates directory. The magic is performed by a special control, Dynam- icControl , which works with GridView and DetailsView to display fields dynamically. Traditionally, you had to use these controls with hard-coded fields, which limits the possibility of providing flexible masks. These controls have been adapted to work eas- ily with these new features provided by Dynamic Data. You can also use other controls, like ListView or FormView , using the same approach. INTEGRATING DYNAMIC DATA CONTROLS IN EXISTING SITES If you need to inte- grate this feature in existing applications, you need to copy the DynamicData directory and global.asax. You can set a different directory for the template using the DynamicDataFolderVirtualPath property on ContextConfigura- tion , as explained on MSDN at http://mng.bz/nNS4. You can read more about adding Dynamic Data to an existing website at http://mng.bz/uQn7. The interesting part is that DynamicControl works with invisible, but useful, informa- tion called metadata. You can use the data annotations features from the System.Com- ponentModel.DataAnnonations namespace to decorate the classes and to provide additional information that Dynamic Data controls can read to understand how a col- umn is composed, which type it holds, and so on. Data annotation is a transversal con- cept, and can be used outside Dynamic Data controls. For example, ASP.NET MVC uses it to automatically build the UI associated with a given model. Figure 5.12 The default page in Dynamic Data will display the list of mapped entities. In Dynamic Data, mapped entities are called tables. 127TECHNIQUE 33 Working with metadata and templates DISCUSSION Dynamic Data controls present a powerful technology that simplifies data entry, where your data strategy coincides with your mapped model. Thanks to data annotations, Dynamic Data controls automatically provide form validation, based on the metadata available. The rendering is associated with specific controls, depending on the data type. Believe it or not, you can extend this behavior even further. You’re going to see that in the next scenario. Working with metadata and templates Dynamic Data controls work with templates, for both views and data types. Each col- umn is rendered according to its type, using a simple mechanism. You can alter this behavior to achieve different results. PROBLEM When you’re dealing with mapped entities coming from a database, the database schema infers some metadata information, such as data type, maximum length, and so on. When data is being displayed, the column name, the validation, or the UI data type might differ from the underlying database schema. Sometimes, you might need different templates. SOLUTION Dynamic Data templates are grouped by type. Page templates are in the Dynamic- Data/PageTemplates folder, where each page represents a different action: ■ List.aspx—Contains a GridView , used to display data. You can specify foreign keys, boolean values, and custom filters using a special control, called DynamicFilter . ■ Edit.aspx—Contains a DetailsView , used to display the data while in editing. ■ Insert.aspx—Used to insert a new item, using a DetailsView. ■ ListDetails.aspx—Can be used to override List.aspx behavior. Provides, on the same page, both a list and edit panel, using a master/detail approach. All the templates share a common base, using a DynamicDataManager to instruct the data controls, a ValidationSummary to display validation errors, and an UpdatePanel to provide AJAX capabilities, using ASP.NET AJAX (see chapter 12). Changing the display behavior Each column is rendered according to its data type, using the appropriate template in the DynamicData/FieldTemplates directory. Table 5.4 describes the types that are supported. Table 5.4 Default field templates in Dynamic Data Template Description Boolean Represents a boolean value using a CheckBox . Children Gets a link that navigates to the child entities, in a relation. DateTime Displays a DateTime value. TECHNIQUE 33 128 CHAPTER 5 Data binding in ASP.NET Web Forms When the type of a column is a non-primitive data type, data annotations come to the rescue. Using the DataTypeAttribute attribute from System.ComponentModel. DataAnnotations , you can specify a type that’s more specific than the CLR type. Using the templates listed in table 5.4, you could map a string property to be represented by the Url template, or by MultilineText . The CLR type, in this kind of situation, remains System.String , but for display purposes you would use a more specific one. Becaus e we’re work in g with autog enerated ent it ies, we need to use an att ribute call ed MetadataType to tell Dynamic Data which class contains metadata information. If you’re using Entity Framework’s POCO support (see chapters 2 and 3), you can use the attribute directly. An example of using MetadataType is shown in the following listing. C#: [MetadataType(typeof(CustomerMetaData))] public partial class Customer {} public class CustomerMetaData { [DataTypeAttribute(DataType.MultilineText)] public string Address { get; set; } } VB: <MetadataType(GetType(CustomerMetaData))> Partial Public Class Customer End Class Public Class CustomerMetaData <DataTypeAttribute(DataType.MultilineText)> Public Address As String End Class Decimal Displays a Decimal value. EmailAddress Represents an email address. The address is clickable. Enumeration Supports enumeration. New in verson 4.0. ForeignKey Displays a link to the foreign key column. Integer Displays an Integer value. ManyToMany Represents a many to many relationship, if that’s supported by the provider. MultilineText Displays multiline text. Text Displays simple text. Url Displays a hyperlink to the given URL. Listing 5.12 Extending the Customer entity with custom attributes Table 5.4 Default field templates in Dynamic Data (continued) Template Description Specify class containing annotations Specify different data type 129TECHNIQUE 33 Working with metadata and templates Generally, the DataTypeAttribute holds one of the values from the DataType enum. (You can fine more information about this enum on MSDN at http://mng.bz/7d3n.) You can specify a string, which forces Dynamic Data to use the corresponding custom template. We’ll talk about custom templates in technique 34. To just control the selected control, without altering the data type, you can use UIHintAttribute , which is specifically targeted at visual rendering. When you specify this attribute, Dynamic Data bypasses the DataTypeAttribute value, which can be accessed in the corresponding custom field template. Changing the display format If you need to change how the value is handled at display time, you need to use Dis- playFormatAttribute . This attribute has interesting properties that handle the for- mat string, null display text, and whether the display should be applied in editing: C#: public class ProductMetadata { [DisplayFormat(ApplyFormatInEditMode = false, DataFormatString = "{0:C}", NullDisplayText = "not set")] public decimal UnitPrice {get; set;} } VB: Public Class ProductMetadata <DisplayFormat(ApplyFormatInEditMode := False, DataFormatString := "{0:C}", NullDisplayText := "not set")> Public Property UnitPrice As Decimal End Class You can see an example in figure 5.13. Figure 5.13 A custom display format is applied to the UnitPrice property. The results will influence how the data is rendered. 130 CHAPTER 5 Data binding in ASP.NET Web Forms This attribute is useful because it provides an advanced format specific to the corre- sponding attribute and column combination. Changing the display name The model is used to represent the entities, which aren’t directly exposed to your users. For this reason, you can specify a display name that’s used to provide a better display name, using DisplayNameAttribute . You can find the results in figure 5.14. The corresponding code is simple: C#: public class ProductMetadata { [DisplayName("Price")] public decimal UnitPrice {get; set;} } VB: Public Class ProductMetadata <DisplayName("Price")> Public Property UnitPrice As Decimal End Class If you need to specify a description, you can use DescriptionAttribute . Hiding tables and columns You can hide tables and columns from the layout completely by setting the Scaffold- Table or ScaffoldColumn property. To hide the Product table, you can use this code: C#: [ScaffoldTable(false)] public class ProductMetadata { } VB: <ScaffoldTable(false) Public Class ProductMetadata End Class If you need to hide a column, the code is similar. DISCUSSION Dynamic Data controls are designed to be extensible. You can control every aspect of page layout and data manipulation, using the data annotations to add specific meaning Figure 5.14 You can specify a custom display name (in this example, Price instead of UnitPrice). Using custom names makes your page more user-friendly. 131TECHNIQUE 34 Extending Dynamic Data to tables and columns. If you need to extend its capabilities even more, read on. We’re going to talk about address validation, custom templates, and searching. Extending Dynamic Data It’s easy to extend Dynamic Data and use advanced features, such as validation or searching. You can achieve interesting results by leveraging specific attributes. PROBLEM In a typical application, you need to validate user input, use a custom template, and integrate your own search criteria. Let’s see how you can integrate these features into Dynamic Data. SOLUTION Validation is probably the most requested feature in data entry. You can’t simply trust the user input; you need to provide a validation mechanism. We’ll start our solution with this problem. Validation Dynamic Data uses the attributes of data annotations to perform validation. You can find more information about all the attributes at http://mng.bz/nqz1. The most interesting attributes for validation are presented in table 5.5. If you want to specify that the UnitPrice property on Product is mandatory and that its value must be between 0 and 100, you’ll write the following code: C#: public class ProductMetadata { [Required] [Range(0, 100, ErrorMessage="Valid only between 0 and 100")] public decimal UnitPrice; } Table 5.5 Data annotation attributes used in validation Template Description CustomValidationAttribute New in ASP.NET 4.0. Using this attribute, you can define rules attached to the entity. RangeAttribute Can be used to specify the valid value range. RegularExpressionAttribute Contains a regular expression to validate the property value. RequiredAttribute Marks the property as required. StringLengthAttribute Defines the string length. ValidationResult Used in custom validation attributes to represent the valida- tion result. TECHNIQUE 34 132 CHAPTER 5 Data binding in ASP.NET Web Forms VB: Public Class ProductMetadata <Required> <Range(0, 100, ErrorMessage := "Valid only between 0 and 100")] Public UnitPrice As Decimal End Class If you run the Dynamic Data site using this modi- fied property, you’ll get the result shown in fig- ure 5.15. You can also provide validation using LINQ to SQL or Entity Framework extensibility. Data anno- tations use attributes and are easier to use in sim- ple scenarios like this one. Building a custom template To build a custom template, you need to create a new user control under the DynamicData\Field- Templates director y. The control must derive from System.Web.DynamicData.FieldTemplate- UserControl , which is the base class used by Dynamic Data to define custom templates. You can define two custom templates: one for the display status and the other for the editing. The edit template must include _edit after the template name and before the .ascx extension. If you omit the edit template, the default one for the type will be used. To specify a custom template, you must use the UIHintAttribute attribute: C#: [UIHintAttribute("Phone")] public string Phone { get; set; } VB: <UIHintAttribute("Phone") Public Property Address As String Save the Phone template inside Dynamic Data’s template directory. To create a simple template, you can use one of the existing ones as a starting point. In our case, the most similar is the Url template, so our new template code will be similar to that shown in the following listing. C#: public partial class PhoneField : System.Web.DynamicData.FieldTemplateUserControl { Listing 5.13 Defining a custom field template to display phone number Figure 5.15 Dynamic Data validation is based on data annotations. You can use attributes to specify custom rules that maintain data consistency. 133TECHNIQUE 34 Extending Dynamic Data protected override void OnDataBinding(EventArgs e) { HyperLinkUrl.NavigateUrl = GetUrl(FieldValueString); } private string GetUrl(string phone) { return string.IsNullOrEmpty(phone) ? "#" : string.Concat("callto:", phone); } public override Control DataControl { get { return HyperLinkUrl; } } } VB: Public Partial Class PhoneField Inherits System.Web.DynamicData.FieldTemplateUserControl Protected Overloads Overrides Sub OnDataBinding(ByVal e As EventArgs) HyperLinkUrl.NavigateUrl = GetUrl(FieldValueString) End Sub Private Function GetUrl(ByVal phone As String) As String Return If(String.IsNullOrEmpty(phone), "#", String.Concat("callto:", phone)) End Function Public Overloads Overrides ReadOnly Property DataControl() As ➥ Control Get Return HyperLinkUrl End Get End Property End Class In our example, the Phone property will be rendered as a hyperlink, using the callto protocol to automatically initiate a Voice over Internet Protocol (VoIP) conversation by clicking on the phone number. The resulting page is shown in figure 5.16. You can extend this approach even further to use it on a complex type. You can use it to attach a WYSIWYG (What You See Is What You Get) editor to specific properties or to provide custom behavior for your application. By inspecting the existing template, you can learn a lot and create your own implementations. Custom filter templates You can customize the search mechanism by writing filter templates. Similar to display templates, you save a filter template under DynamicData\Filters, and the user control must inherit from System.Web.DynamicData.QueryableFilterUserControl . To implement this behavior, you must understand how IQueryable works and know something about LINQ, lambda, and Func<T> . You can read more about this topic on MSDN at http://mng.bz/YKP4. Display value Format callto link Control used by template Display value Format callto link Control used by template 134 CHAPTER 5 Data binding in ASP.NET Web Forms DISCUSSION You can enhance and customize Dynamic Data controls to suit your needs. The new version available with ASP.NET 4.0 introduces some new, long-awaited features, like custom filters, custom page templates, new templates, and better integration with existing and custom providers. If you need to provide a dynamic data entry interface, you can do it easily with Dynamic Data controls. 5.5 Summary Data binding is a central topic in every ASP.NET application. Data binding isn’t neces- sarily tied to a database as a data source. You can, in fact, get data from different kinds of sources, and perform the same step to display the data. This is the first advantage of using data binding: you can use the same techniques to display data coming from dif- ferent sources. ASP.NET supports data binding in different ways, by providing specific controls to display data (called data controls) and other controls to get data without writing code (called data source controls). You’ll find that using controls to get data is useful in some situations, and you can always write code if you prefer more control over the results. The important thing to remember is that the data controls can display data, and provide sorting, paging, and editing capabilities. You choose whether you want to automate ASP.NET data source controls, or if you just want to write code. Dynamic Data controls have a new, exciting platform that you can use to build pow- erful, visually rich data entry forms without writing code. Instead, you use the power behind Entity Framework and LINQ to SQL, which you can extend in ASP.NET 4.0 to cus- tom providers. You can enhance the platform by writing specific code and achieve inter- esting and useful results. We’ll continue our examination of ASP.NET Web Forms by looking at how you can use custom controls to enhance componentization. Let’s get to it. Figure 5.16 The custom template for the phone number in action. You can specify custom behaviors and provide better usability for your users. [...]... true); HyperLink link = new HyperLink(); link.NavigateUrl = postBackLink; link.Text = "Test PostBack"; link.RenderControl(writer); } VB: Protected Overrides Sub RenderContents(writer As HtmlTextWriter) Dim postBackLink As String = Page.ClientScript.GetPostBackClientHyperlink(Me, Value.ToString(), True) Dim link As New HyperLink() link.NavigateUrl = postBackLink link.Text = "Test PostBack" link.RenderControl(writer)... data binding The OnDataBinding method inherited from Control is overridden to invoke the EnsureChildControls method D; this guarantees that child controls in the template are created before the data binding takes place Because our template will just show some text, the corresponding template container has only one property, which makes things simple All the code is contained in the following listing... keep in mind when you’re building custom controls It lets you freely define a visual appearance for your page that can be changed without you rewriting the code This scenario leads us directly into the next one, where we’re going to address how to use data binding in custom controls TECHNIQUE 40 Data binding in custom controls To show how data binding works, we need to define a scenario that’s more complex... brush up on ASP.NET Web Forms, be sure that you’ve read chapters 4 and 5 In this chapter, we’ll take a look at how to build custom controls, starting with the simple ones After that, we’ll move on to analyzing more complex scenarios, such as data binding and templating Most of the topics presented here aren’t entirely new to ASP.NET 4. 0, but they’re definitely important if you’re working with ASP.NET 6.1... container to enhance the look of your of our work in this section control In this example, we’re taking a Although this exercise was useful so that value from the control and formatting it you could understand how templated controls work, this example is limited in use because data binding isn’t performed in the strict sense of its meaning DISCUSSION Templating is an important thing to keep in mind... a container control works To instruct the Page Parser that the control is a container, you need to implement the INamingContainer interface As previously noted, this interface is only a marker interface, so you don’t have to write any code The Page Parser will find the interface Container Control1 ClientID ControlID Control1 Controln ClientID ControlID Controln Figure 6.5 A container control influences... following code checks the DataSource property and adds EmptyTemplate if it’s needed: C#: if (dataBinding) { if (DataSource == null) { if (EmptyTemplate != null) TECHNIQUE 40 Data binding in custom controls 155 { this.Controls.Clear(); EmptyTemplate.InstantiateIn(this); } } else } VB: If dataBinding Then If DataSource Is Nothing Then If EmptyTemplate IsNot Nothing Then Me.Controls.Clear() EmptyTemplate.InstantiateIn(Me)... ItemTemplate property is displaying the source On the right, the EmptyTemplate was instantiated data binding, you can build a powerful control in few lines, and you get great performance with maximum flexibility DISCUSSION Data binding is a powerful feature in ASP.NET Web Forms You can build rich layouts without duplicating any code If you need special behavior in data binding, you can create a custom... ones, enhancing their features In most situations, this process consists of picking two or more controls and combining them to produce a single result Knowing how to do this is important 140 CHAPTER 6 Custom controls because you can reuse existing controls and add more features to simplify the use of common, recurring situations We’re talking about composite controls separately because combining controls... generated by using the GetPostBackClientHyperlink method offered by ClientScript, which is accessible through the current Page instance The code is shown in the following listing Listing 6 .4 A simple control that generates a link for a PostBack C#: protected override void RenderContents(HtmlTextWriter writer) { string postBackLink = Page.ClientScript.GetPostBackClientHyperlink(this, Value.ToString(), true); . result. TECHNIQUE 34 132 CHAPTER 5 Data binding in ASP. NET Web Forms VB: Public Class ProductMetadata <Required> <Range (0, 100 , ErrorMessage := "Valid only between 0 and 100 ")] . extend in ASP. NET 4. 0 to cus- tom providers. You can enhance the platform by writing specific code and achieve inter- esting and useful results. We’ll continue our examination of ASP. NET Web. existing control and enrich it. Depending on your needs, you can interact with the Web Form during PostBacks, or support data binding (introduced in chapter 5). One of the most interesting aspects

Ngày đăng: 12/08/2014, 15:23

TỪ KHÓA LIÊN QUAN