我有一个基本的Web表单项目,使用Entity Frameworks& SQL Server for data。我正在尝试将GridView连接到表,由于某种原因,UpdateMethod不会被调用。当单击“更新”链接但它永远不会到达gvNames_UpdateItem时,它会进行回发。任何帮助将不胜感激。
<asp:GridView ID="gvNames" runat="server" SelectMethod="gvNames_GetData" UpdateMethod="gvNames_UpdateItem"
DeleteMethod="gvNames_DeleteItem" CssClass="table table-hover table-striped"
UseAccessibleHeader="true" ItemType="CountyPMFraudData.NotifyName" AutoGenerateColumns="false" DataKeyNames="NotifyNamesID"
ShowHeaderWhenEmpty="true" OnPreRender="gvNames_PreRender" >
<Columns>
<asp:DynamicField DataField="NotifyNamesID" Visible="false" />
<asp:DynamicField DataField="UserID" Visible="false" />
<asp:DynamicField DataField="CorpFlag" HeaderText="Business" />
<asp:DynamicField DataField="FirstName" />
<asp:DynamicField DataField="LastName" HeaderText="Last Name/Business Name" />
<asp:DynamicField DataField="Active" HeaderText="Active" />
<asp:CommandField ShowEditButton="true" ShowCancelButton="true" ShowDeleteButton="true"/>
</Columns>
</asp:GridView>
这就是背后的代码:
public void gvNames_DeleteItem(int notifyNamesID)
{
using (var dbContext = new CountyPMFraudEntities())
{
var item = new NotifyName { NotifyNamesID = notifyNamesID };
dbContext.Entry(item).State = EntityState.Deleted;
try
{
dbContext.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
ValidationError.Display(String.Format("Item with id {0} no longer exists in the database.", notifyNamesID));
}
}
}
public IEnumerable gvNames_GetData()
{
List<NotifyName> names = null;
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
using (var dbContext = new CountyPMFraudEntities())
{
names = dbContext.NotifyNames.Where(NotifyName => NotifyName.UserID == _userID).ToList();
}
}
return names;
}
public void gvNames_UpdateItem(int notifyNamesID)
{
using (var dbContext = new CountyPMFraudEntities())
{
var name = dbContext.NotifyNames.Find(notifyNamesID);
if (name == null)
{
ValidationError.Display(String.Format("Item with id {0} was not found", notifyNamesID));
return;
}
TryUpdateModel(name);
if (ModelState.IsValid)
{
dbContext.SaveChanges();
}
}
}
protected void gvNames_PreRender(object sender, EventArgs e)
{
try
{
gvNames.HeaderRow.TableSection = TableRowSection.TableHeader;
}
catch (Exception)
{
//Just ignore becuase there is no data.
}
}
答案 0 :(得分:0)
好的,我想出来了。有两件事正在发生。首先,我错过了添加&#34; ValidationSummary&#34;并启用ShowModelStateErrors,如下所示:
<asp:ValidationSummary ID="vsHuman" ShowModelStateErrors="true" ValidationGroup="vgHuman" runat="server" ForeColor="Red" />
一旦我这样做,我意识到我收到错误&#34; NotifyNamesID字段是必需的。&#34;。有了这个,我出于某种原因发现了隐藏的&#34; DynamicField&#34;回到服务器时没有包含数据,因此我不得不将其更改为这样的TemplateField:
<asp:TemplateField Visible="false">
<ItemTemplate>
<asp:HiddenField runat="server" Value='<%#Eval("NotifyNamesID") %>' />
</ItemTemplate>
</asp:TemplateField>
一旦我这样做,事情就开始起作用了。希望这有助于将来的某些人。