asp.net 中的 TryUpdateModel 如何工作?

how does TryUpdateModel in asp.net work?

开发于:ASP.net Web 表单 4.5

我目前正在使用 DynamicDataTemplateCS Nuget 按照这里的教程打包:https://docs.microsoft.com/en-us/aspnet/web-forms/overview/presenting-and-managing-data/model-binding/updating-deleting-and-creating-data

它启用了自动生成更新方法和删除方法,因为我使用它们并且没有问题。但是现在我稍微更改了数据以显示信息 不是来自 gridview 的 itemtemplate 字段上的 table。

我查看了代码并输入了 print 语句,它似乎进入了 TryUpdateModel 方法并输出了 true,但它没有更新数据库。

代码是这样的: 观看次数:

    <asp:GridView runat="server" ID="aGrid" CellPadding="10" 
    DataKeyNames="idx" AutoGenerateColumns="false"
    selectMethod="aGrid_GetData" ItemType="model"
    updateMethod="aGrid_UpdateItem" AutoGenerateEditButton="true"
    deleteMethod="aGrid_DeleteItem" AutoGenerateDeleteButton="true"
    onRowDataBound="aGrid_RowDataBound">
    <Columns>
        <asp:DynamicField DataField="poNum"  />
        <asp:BoundField DataField="a" HeaderText="a"/>
        <asp:DynamicField DataField="someDate" DataFormatString="{0:d}" />
        <asp:BoundField HeaderText="b" />
        <asp:HyperLinkField HeaderText="c"  NavigateUrl="~/yes?no={0}" />
        <asp:DynamicField DataField="e" />
        <asp:DynamicField DataField="f" />
        <asp:DynamicField DataField="g" DataformatString="{0:d}"/>
        <asp:DynamicField DataField="h" />
    </Columns>
</asp:GridView>

后端:

    public void aGrid_UpdateItem(int idx)
    {
        using (Context db = new Context())
        {
            model item = null;
            item = db.model.Find(idx);
            System.Diagnostics.Debug.WriteLine("updatemethod started");

            if (item == null)
            {
                // The item wasn't found
                System.Diagnostics.Debug.WriteLine("item is null");

                ModelState.AddModelError("", String.Format("Item with id {0} was not found", idx));
                return;
            }
            System.Diagnostics.Debug.WriteLine("trying to update model");


            System.Diagnostics.Debug.WriteLine(TryUpdateModel(item));
            //TryUpdateModel(item);
            if (ModelState.IsValid)
            {
                System.Diagnostics.Debug.WriteLine("before saving changes");
                db.SaveChanges();
                System.Diagnostics.Debug.WriteLine("after saving changes");
                // Save changes here, e.g. MyDataLayer.SaveChanges();
            }
            else
            {
                System.Diagnostics.Debug.WriteLine("ModelState not valid!!");
            }
        }
    }

我不明白为什么不更新.. 我怀疑这两个 BoundFields "b" 和 "c" 因为实际上它们的数据不是 从模型。我绑定了它们 outside.Anyways,最好知道 TryUpdateModel 是如何工作的,这样我就可以弄清楚为什么它不起作用。

顺便说一下,这是我绑定 "b" 和 "c" 字段的代码。 当我在视图中将它们注释掉时,更新有效,因此他们感到内疚 TryUpdateModel 不工作。

    protected void aGrid_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        using (thisAction ta = new thisAction())
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {

                string str = e.Row.Cells[2].Text;
                if (str.Length > 0)
                {
                    string str2 = soa.get_str2(str);
                    e.Row.Cells[4].Text = str2;

                    string str3 = soa.get_str3(str);
                    e.Row.Cells[5].Text = str3;
                }

            }
        }
    }

PS : 我为命名道歉..它有一些敏感数据所以我不得不改变它们

我在 asp.net 论坛上 post 编辑了这篇文章,有人回答了...将 post 这篇文章供将来参考,但功劳归于 Cathy Zou。谢谢凯茜。

嗨 jimmythegreat,

TryUpdateModel 方法将匹配的数据绑定值从 Web 表单应用到数据项。根据id参数的值获取数据项。

因此,数据绑定应与实体中归档的数据相匹配(ItemType="WingtipToys.Models.Student")

因此,您不应该使用 BoundFields(b 和 c),因为它们的数据不是来自模型;

我根据您提供的教程制作了一个工作示例:

<asp:GridView runat="server" ID="studentsGrid"
            ItemType="WingtipToys.Models.Student" DataKeyNames="StudentID"
            SelectMethod="studentsGrid_GetData"
          UpdateMethod="studentsGrid_UpdateItem1" 
DeleteMethod="studentsGrid_DeleteItem"
            AutoGenerateEditButton="true" AutoGenerateDeleteButton="true"
            AutoGenerateColumns="false">
            <Columns>
                <asp:DynamicField DataField="StudentID" />
                <asp:DynamicField DataField="LastName" />
                <asp:DynamicField DataField="FirstName" />
                <asp:DynamicField DataField="Year" />
                <asp:TemplateField HeaderText="Total Credits">
                    <ItemTemplate>
                        <asp:Label Text="<%# Item.Enrollments.Sum(en => en.Course.Credits) %>"
                            runat="server" />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>

代码隐藏:

using WingtipToys.Models;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;

  public IQueryable<Student> studentsGrid_GetData()
        {
        SchoolContext db = new SchoolContext();
        var query = db.Students.Include(s => s.Enrollments.Select(e => e.Course));
        return query;
    }
    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;
            }

            UpdateModel(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;
            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                ModelState.AddModelError("",
                  String.Format("Item with id {0} no longer exists in the database.", studentID));
            }
        }
    }

此致

凯茜

link : https://forums.asp.net/t/2133078.aspx?How+does+TryUpdateModel+work+