asp.net中的TryUpdateModel如何工作?

时间:2017-12-08 21:48:04

标签: asp.net gridview webforms .net-4.5 model-binding

开发: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

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

我查看了代码并输入了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&#34; b&#34;和&#34; c&#34;因为实际上他们的数据不是 从模型。我把它们绑在外面。不管怎样,最好知道TryUpdateModel是如何工作的,这样我就可以弄清楚为什么这不起作用。

顺便说一句,这是我绑定的代码&#34; b&#34;和&#34; c&#34;领域。 当我在视图中对它们进行评论时,更新有效,因此他们感到内疚 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:我为命名道歉..它有一些敏感的数据所以我不得不改变它们

1 个答案:

答案 0 :(得分:0)

我在asp.net论坛上发布了此消息并且有人回答...将发布此信息以供将来参考,但是归功于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+