Paul Cociuba is back with the 6th part of his ASP.NET 4.5 journey. As promised last time around he will look at CRUD operations using strongly typed data binding.


In this video I will continue how to use strongly typed data binding features from ASP.net WebForms 4.5 to accomplish the rest of the common operations on data: insert, update and delete, and how these features can be leveraged with the data-controls that come with the product. Up to now, I have only been using strongly data-binding when reading data, via the Item. property which is exposed on the page and typed to the model via the ItemType property of the data control.

Let’s roll the video!

For convenience, here is a timeline of the video:

  • [1:10]: In the CategoryDetails.aspx page that is used to show the details of a given category, we will add two more templates to the FormView control on the page. For now, the control only had an ItemTemplate, which is the template used for displaying data. These templates will be the InsertItemTemplate and the EditItemTemplate used for inserting and editing data respectively.
  • [2:15]: Once the markup for the templates is complete, we will modify the controls in the templates to allow for inserting and editing of data. Instead of using the Item. property on the page, we now use the BindItem. property which allows for two way data-binding to and from the model object.

To HTML encode data coming from the model, and sanitize what will be displayed, we can use a new operator introduced in ASP.net 4.5: the <%: instead of the <%# as such:

<asp:Label id:lblCategoryName runat=”server” Text=’<%: BindItem.Name %>’ />

This will encode the value of the Name property of the model object before it is incorporated into the markup of the page that is to be sent back to the client browser.

  • [4:40]: When building out the txtCategoryDescription textbox, we will need to display a multi-line input to accommodate for longer description fields. We do this by using the TextMode attribute of a textbox control and giving it a value of ‘multiline’. In ASP.net 4.5, this control has been enhanced to include all of the possible HTML values for HTML 5 – such as Color (to display a color picker), datetime (to display a date-time picker), time, range and so on.
  • [6:30] In order to finish work on the InsertItemTemplate and EditItemTemplate, we also provide the user with a way of switching between the different modes (templates) of the form view control. This is done by appending LinkButtons on each of the templates. For the ItemTemplate these buttons have a Command attribute set to special values – ‘new’ to switch to Insert view, ‘edit’ to switch to Edit view and ‘delete’ to ask to control to delete the current item.
  • [7:50] For the InsertItemTemplate, the values of the Command attribute on the buttons are ‘insert’ which prompts the control to create and insert a new model object into the persistent store, and ‘cancel’ which cancels the operation.
  • [8:03] For the EditItemTemplate, the values of the Command attribute on the buttons are ‘update’ to prompt the control to attempt to update the existing model object with new data and ‘cancel’.
  • [8:30] In order for the FormView control to be able to perform the insert, update and delete operations, the final stage is to tell the control what methods on the code behind of the page are to be invoked to perform each one of these tasks. This is done by the InsertMethod, UpdateMethod and DeleteMethod attributes of the control in markup.
  • [9:10] Now that the FormView control is hooked up to the code behind methods, we have to implement these methods and the logic behind them to actually perform the operations.
  • [9:50] InsertToyCategory will be the name of the code-behind method responsible for inserting new model objects when called by the FormView control. The method first creates a new empty ToyCategory model object, then appends it to the existing data context object (which is of type ProductContext) using the .Add() method. Following this, the values of the fields in the InsertItemTemplate of the FormView control will be transferred to the new model object by issuing a call to TryUpdateModel() which is another method provided directly by the Page object in ASP.net, to invoke the model binder. Finally, the method will save the new object by calling the SaveChanges() method on the data-context object on the page.
  • [11:30] UpdateToyCategory is the name of the code-behind method that will be used to update a model object once the user has made changes to it via the FormView control. This method uses an input parameter of type int called CategoryID, which will automatically be populated by the FormView when the end user requests that an update be perform. How does the form view know that this is the parameter to populate? By inspecting the model type (via the ItemType property) and the primary key property on the model which is given by the ‘DataKeyNames’ attribute. The method looks up a ToyCategory object in the data-context by using the Find() method. This method will take an argument and try to match the value of the argument passed in to a primary key on the table in the database. Should a match be found, we try and transfer the values of the fields from the FormView’s EditItemTemplate template to the object via the TryUpdateModel() method call, and then persist it back to the database via the SaveChanges() method.
  • [12:25] – DeleteToyCategory is the name of the code behind method used to delete an existing model object when the end user requests the FormView do so by clicking on the LinkButon with the command property set to ‘delete’. This method works much like the update method: it attempts to find the object to delete via the Find() method call on the data-context, and then, attempts to remove the object by issuing a call to Delete() on the data-context.
  • [13:35] – To finish the scenario, three more event handlers are needed to handle the ItemInserted event, ItemDeleted event and ItemCommand event. The first two (insert and delete) will just redirect to the category listings page (Categories.aspx) following an insert of delete of a model object. The ItemCommand event handler will check if the command argument (specified by the command attribute of the LinkButtons) is equal to the value ‘cancel’ and if so, it will also redirect to the category listings page.
  • [15:20] – To tell Entity Framework a little bit more on how we would like to model to be generated, we will use the System.ComponentModel.DataAnnotations namespace. This namespace allows the usage of a wide list of attributes with which the properties of the ToyCategory object (defined in the ToyCategory.cs file) can be decorated. Some attributes that will be used include the [Key] attribute to specify the column with that is to be the primary key, [Display] attribute, to be used as the display name for a property, or the [Range] attribute to be used to limit input values on a property to a given range.
  • [16:50] – Finally, we add a button on the Categories.aspx page to allow the navigation to the CategoryDetails.aspx page and insertion of a new Category. This is done by specifying a query string value of ‘command=new’ which will be captured by the Page_Load event of the CategoryDetails.aspx page to will be used to change the mode of the FormView to insert via the ChangeMode() method, so that the InsertItemTemplate is displayed by default.
  • [18:20] – We start testing the newly added code, by looking at the step by step execution of an insert call from the FormView.
  • [20:30] – Once a new ToyCategory object has been created, we also have a look at the step by step execution of an update command from the FormView to understand how the code works.

Whew! That’s it for now! In the next part, we will look at how we can improve the way the URLs of the application look like by using Routing – a concept first made popular by ASP.net MVC.

See you soon!


Original content from Paul Cociuba; posted by MSPFE Editor Arvind Shyamsundar