作者 Tom FitzMacken

本教程系列演示了将模型绑定与 ASP.NET Web Forms项目配合使用的基本方面。 模型绑定比处理数据源对象 ((如 ObjectDataSource 或 SqlDataSource) )更直接。 本系列从介绍性材料开始,并在后续教程中转到更高级的概念。

本教程演示如何使用模型绑定创建、更新和删除数据。 将设置以下属性:

  • DeleteMethod
  • InsertMethod
  • UpdateMethod
  • 这些属性接收处理相应操作的方法的名称。 在该方法中,提供用于与数据交互的逻辑。

    本教程基于在系列的第一 部分 创建的项目。

    可以在 C# 或 VB 中 下载 完整的项目。 可下载的代码适用于 Visual Studio 2012 或 Visual Studio 2013。 它使用 Visual Studio 2012 模板,与本教程中显示的Visual Studio 2013模板略有不同。

    在本教程中,你将:

  • 添加动态数据模板
  • 通过模型绑定方法启用更新和删除数据
  • 应用数据验证规则 - 启用在数据库中创建新记录
  • 添加动态数据模板

    为了提供最佳用户体验并最大程度地减少代码重复,你将使用动态数据模板。 通过安装 NuGet 包,可以轻松地将预生成的动态数据模板集成到现有站点中。

    “管理 NuGet 包 ”中,安装 DynamicDataTemplatesCS

    请注意,项目现在包含名为 DynamicData 的文件夹。 在该文件夹中,你将找到自动应用于 Web 窗体中的动态控件的模板。

    启用更新和删除

    使用户能够更新和删除数据库中的记录与检索数据的过程非常相似。 在 UpdateMethod DeleteMethod 属性中,指定执行这些操作的方法的名称。 使用 GridView 控件,还可以指定自动生成编辑和删除按钮。 以下突出显示的代码显示了 GridView 代码的新增内容。

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

    在代码隐藏文件中,为 System.Data.Entity.Infrastructure 添加 using 语句。

    using System.Data.Entity.Infrastructure;
    

    然后,添加以下更新和删除方法。

    public void studentsGrid_UpdateItem(int studentID)
        using (SchoolContext db = new SchoolContext())
            Student item = null;
            item = db.Students.Find(studentID);
            if (item == null)
                ModelState.AddModelError("", 
                  String.Format("Item with id {0} was not found", studentID));
                return;
            TryUpdateModel(item);
            if (ModelState.IsValid)
                db.SaveChanges();
    public void studentsGrid_DeleteItem(int studentID)
        using (SchoolContext db = new SchoolContext())
            var item = new Student { StudentID = studentID };
            db.Entry(item).State = EntityState.Deleted;
                db.SaveChanges();
            catch (DbUpdateConcurrencyException)
                ModelState.AddModelError("", 
                  String.Format("Item with id {0} no longer exists in the database.", studentID));
    

    TryUpdateModel 方法将 Web 窗体中的匹配数据绑定值应用于数据项。 根据 ID 参数的值检索数据项。

    强制实施验证要求

    在更新数据时,会自动强制执行应用于 Student 类中的 FirstName、LastName 和 Year 属性的验证属性。 DynamicField 控件基于验证属性添加客户端和服务器验证程序。 FirstName 和 LastName 属性均是必需的。 FirstName 长度不能超过 20 个字符,LastName 不能超过 40 个字符。 Year 必须是 AcademicYear 枚举的有效值。

    如果用户违反某个验证要求,则不会继续更新。 若要查看错误消息,请在 GridView 上方添加 ValidationSummary 控件。 若要显示模型绑定中的验证错误,请将 ShowModelStateErrors 属性设置为 true

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

    运行 Web 应用程序并更新和删除任何记录。

    请注意,在编辑模式下,Year 属性的值会自动呈现为下拉列表。 Year 属性是枚举值,枚举值的动态数据模板指定用于编辑的下拉列表。 可以通过在 DynamicData/FieldTemplates 文件夹中打开 Enumeration_Edit.ascx 文件来找到该模板。

    如果提供有效值,更新将成功完成。 如果违反某个验证要求,则更新不会继续,并且网格上方会显示一条错误消息。

    添加新记录

    GridView 控件不包含 InsertMethod 属性,因此不能用于添加具有模型绑定的新记录。 可以在 FormView、DetailsViewListView 控件中找到 InsertMethod 属性。 在本教程中,你将使用 FormView 控件添加新记录。

    首先,添加指向要创建新记录的新页面的链接。 在 ValidationSummary 上方添加:

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

    新链接将显示在“学生”页面的内容顶部。

    然后,使用母版页添加新的 Web 窗体,并将其命名为 AddStudent。 选择 Site.Master 作为母版页。

    你将使用 DynamicEntity 控件呈现用于添加新学生的字段。 DynamicEntity 控件呈现 ItemType 属性中指定的类中的可编辑属性。 StudentID 属性标有 [基架Column (false) ] 属性,因此不会呈现该属性。 在 AddStudent 页的 MainContent 占位符中,添加以下代码。

    <asp:ValidationSummary runat="server" ShowModelStateErrors="true" />
    <asp:FormView runat="server" ID="addStudentForm"
        ItemType="ContosoUniversityModelBinding.Models.Student" 
        InsertMethod="addStudentForm_InsertItem" DefaultMode="Insert"
        RenderOuterTable="false" OnItemInserted="addStudentForm_ItemInserted">
        <InsertItemTemplate>
            <fieldset>
                    <asp:DynamicEntity runat="server" Mode="Insert" />
                <asp:Button runat="server" Text="Insert" CommandName="Insert" />
                <asp:Button runat="server" Text="Cancel" CausesValidation="false" OnClick="cancelButton_Click" />
            </fieldset>
        </InsertItemTemplate>
    </asp:FormView>
    

    在代码隐藏文件中 (AddStudent.aspx.cs) ,为 ContosoUniversityModelBinding.Models 命名空间添加 using 语句。

    using ContosoUniversityModelBinding.Models;
    

    然后,添加以下方法以指定如何插入新记录和取消按钮的事件处理程序。

    public void addStudentForm_InsertItem()
        var item = new Student();
        TryUpdateModel(item);
        if (ModelState.IsValid)
            using (SchoolContext db = new SchoolContext())
                db.Students.Add(item);
                db.SaveChanges();
    protected void cancelButton_Click(object sender, EventArgs e)
        Response.Redirect("~/Students");
    protected void addStudentForm_ItemInserted(object sender, FormViewInsertedEventArgs e)
        Response.Redirect("~/Students");
    

    保存所有更改。

    运行 Web 应用程序并创建新学生。

    单击 “插入 ”并注意到新学生已创建。

    在本教程中,你启用了更新、删除和创建数据。 确保在与数据交互时应用验证规则。

    在本系列的下一 教程 中,你将启用排序、分页和筛选数据。

    上一页下一页