【发布时间】:2017-12-08 21:48:03
【问题描述】:
开发:ASP.net web forms 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字段的表格。
我查看了代码并输入了打印语句,它似乎进入了 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" 因为实际上它们的数据不是 从模型。我将它们绑定在外面。无论如何,最好知道 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:我为命名道歉..它有一些敏感数据,所以我不得不改变它们
【问题讨论】:
-
当我隐藏这两个字段时它确实有效。 “b”和“c”现在这些字段实际上是有罪的。
标签: asp.net gridview webforms .net-4.5 model-binding