"
ASP.NET (snapshot 2017) Microsoft documentation and samples

Updating, deleting, and creating data with model binding and web forms

by Tom FitzMacken

This tutorial series demonstrates basic aspects of using model binding with an ASP.NET Web Forms project. Model binding makes data interaction more straight-forward than dealing with data source objects (such as ObjectDataSource or SqlDataSource). This series starts with introductory material and moves to more advanced concepts in later tutorials.

This tutorial shows how to create, update, and delete data with model binding. You will set the following properties:

  • DeleteMethod
  • InsertMethod
  • UpdateMethod

These properties receive the name of the method that handles the corresponding operation. Within that method, you provide the logic for interacting with the data.

This tutorial builds on the project created in the first part of the series.

You can download the complete project in C# or VB. The downloadable code works with either Visual Studio 2012 or Visual Studio 2013. It uses the Visual Studio 2012 template, which is slightly different than the Visual Studio 2013 template shown in this tutorial.

What you’ll build

In this tutorial, you’ll:

  1. Add dynamic data templates
  2. Enable updating and deleting data through model binding methods
  3. Apply data validation rules - Enable creating a new record in the database

Add dynamic data templates

To provide the best user experience and minimize code repetition, you will use dynamic data templates. You can easily integrate pre-built dynamic data templates into your existing site by installing a NuGet package.

From the Manage NuGet Packages, install the DynamicDataTemplatesCS.

dynamic data templates
dynamic data templates

Notice that your project now includes a folder named DynamicData. In that folder, you will find the templates that are automatically applied to dynamic controls in your web forms.

dynamic data folder
dynamic data folder

Enable updating and deleting

Enabling users to update and delete records in the database is very similar to the process for retrieving data. In the UpdateMethod and DeleteMethod properties, you specify the names of the methods that perform those operations. With a GridView control, you can also specify the automatic generation of edit and delete buttons. The following highlighted code shows the additions to the GridView code.

[!code-aspxMain]

   1:  <asp:GridView runat="server" ID="studentsGrid"
   2:      ItemType="ContosoUniversityModelBinding.Models.Student" DataKeyNames="StudentID"
   3:      SelectMethod="studentsGrid_GetData"
   4:      UpdateMethod="studentsGrid_UpdateItem" DeleteMethod="studentsGrid_DeleteItem"
   5:      AutoGenerateEditButton="true" AutoGenerateDeleteButton="true"  
   6:      AutoGenerateColumns="false">

In the code-behind file, add a using statement for System.Data.Entity.Infrastructure.

[!code-csharpMain]

   1:  using System.Data.Entity.Infrastructure;

Then, add the following update and delete methods.

[!code-csharpMain]

   1:  public void studentsGrid_UpdateItem(int studentID)
   2:  {
   3:      using (SchoolContext db = new SchoolContext())
   4:      {
   5:          Student item = null;
   6:          item = db.Students.Find(studentID);
   7:          if (item == null)
   8:          {
   9:              ModelState.AddModelError("", 
  10:                String.Format("Item with id {0} was not found", studentID));
  11:              return;
  12:          }
  13:                
  14:          TryUpdateModel(item);
  15:          if (ModelState.IsValid)
  16:          {
  17:              db.SaveChanges();
  18:          }
  19:      }
  20:  }
  21:   
  22:  public void studentsGrid_DeleteItem(int studentID)
  23:  {
  24:      using (SchoolContext db = new SchoolContext())
  25:      {
  26:          var item = new Student { StudentID = studentID };
  27:          db.Entry(item).State = EntityState.Deleted;
  28:          try
  29:          {
  30:              db.SaveChanges();
  31:          }
  32:          catch (DbUpdateConcurrencyException)
  33:          {
  34:              ModelState.AddModelError("", 
  35:                String.Format("Item with id {0} no longer exists in the database.", studentID));
  36:          }
  37:      }
  38:  }

The TryUpdateModel method applies the matching data-bound values from the web form to the data item. The data item is retrieved based on the value of the id parameter.

Enforce validation requirements

The validation attributes that you applied to the FirstName, LastName, and Year properties in the Student class are automatically enforced when updating the data. The DynamicField controls add client and server validators based on the validation attributes. The FirstName and LastName properties are both required. FirstName cannot exceed 20 characters in length, and LastName cannot exceed 40 characters. Year must be a valid value for the AcademicYear enumeration.

If the user violates one of the validation requirements, the update does not proceed. To see the error message, add a ValidationSummary control above the GridView. To display the validation errors from model binding, set the ShowModelStateErrors property set to true.

[!code-aspxMain]

   1:  <asp:ValidationSummary ShowModelStateErrors="true" runat="server" />

Run the web application, and update and delete any of the records.

update data
update data

Notice that when in the edit mode the value for the Year property is automatically rendered as a drop down list. The Year property is an enumeration value, and the dynamic data template for an enumeration value specifies a drop down list for editing. You can find that template by opening the Enumeration_Edit.ascx file in the DynamicData/FieldTemplates folder.

If you provide valid values, the update completes successfully. If you violate one of the validation requirements, the update does not proceed and an error message is displayed above the grid.

error message
error message

Add new records

The GridView control does not include the InsertMethod property and therefore cannot be used for adding a new record with model binding. You can find the InsertMethod property in the FormView, DetailsView, or ListView controls. In this tutorial, you will use a FormView control to add a new record.

First, add a link to the new page you will create for adding a new record. Above the ValidationSummary, add:

[!code-aspxMain]

   1:  <asp:HyperLink NavigateUrl="~/AddStudent" Text="Add New Student" runat="server" />

The new link will appear at the top of the content for the Students page.

new link
new link

Then, add a new web form using a master page, and name it AddStudent. Select Site.Master as the master page.

You will render the fields for adding a new student by using a DynamicEntity control. The DynamicEntity control renders that editable properties in the class specified in the ItemType property. The StudentID property was marked with the [ScaffoldColumn(false)] attribute so it is not rendered. In the MainContent placeholder of the AddStudent page, add the following code.

[!code-aspxMain]

   1:  <asp:ValidationSummary runat="server" ShowModelStateErrors="true" />
   2:  <asp:FormView runat="server" ID="addStudentForm"
   3:      ItemType="ContosoUniversityModelBinding.Models.Student" 
   4:      InsertMethod="addStudentForm_InsertItem" DefaultMode="Insert"
   5:      RenderOuterTable="false" OnItemInserted="addStudentForm_ItemInserted">
   6:      <InsertItemTemplate>
   7:          <fieldset>
   8:              <ol>
   9:                  <asp:DynamicEntity runat="server" Mode="Insert" />
  10:              </ol>
  11:              <asp:Button runat="server" Text="Insert" CommandName="Insert" />
  12:              <asp:Button runat="server" Text="Cancel" CausesValidation="false" OnClick="cancelButton_Click" />
  13:          </fieldset>
  14:      </InsertItemTemplate>
  15:  </asp:FormView>

In the code-behind file (AddStudent.aspx.cs), add a using statement for the ContosoUniversityModelBinding.Models namespace.

[!code-csharpMain]

   1:  using ContosoUniversityModelBinding.Models;

Then, add the following methods to specify how to insert a new record and an event handler for the cancel button.

[!code-csharpMain]

   1:  public void addStudentForm_InsertItem()
   2:  {
   3:      var item = new Student();
   4:              
   5:      TryUpdateModel(item);
   6:      if (ModelState.IsValid)
   7:      {
   8:          using (SchoolContext db = new SchoolContext())
   9:          {
  10:              db.Students.Add(item);
  11:              db.SaveChanges();
  12:          }
  13:      }
  14:  }
  15:   
  16:  protected void cancelButton_Click(object sender, EventArgs e)
  17:  {
  18:      Response.Redirect("~/Students");
  19:  }
  20:   
  21:  protected void addStudentForm_ItemInserted(object sender, FormViewInsertedEventArgs e)
  22:  {
  23:      Response.Redirect("~/Students");
  24:  }

Save all of the changes.

Run the web application and create a new student.

add new student
add new student

Click Insert and notice the new student has been created.

display new student
display new student

Conclusion

In this tutorial, you enabled updating, deleting, and creating data. You ensured validation rules are applied when interacting with the data.

In the next tutorial in this series, you will enable sorting, paging, and filtering data.

Previous Next



Comments ( )
Link to this page: //www.vb-net.com/AspNet-DocAndSamples-2017/aspnet/web-forms/overview/presenting-and-managing-data/model-binding/updating-deleting-and-creating-data.htm
< THANKS ME>