我在一个 Web 应用程序中有两个站点。我想要做的是使用按钮从站点 B 中的 Web 部件更新站点 A 的列表。
问题是,如果我不使用Page.IsPostBack
,单击按钮时页面会引发未处理的异常,但是,站点 A 中的列表会更新。但是,如果我使用Page.IsPostBack
,我不会得到异常,但该过程不会通过;事实上,当按钮被点击时,它甚至不会进入事件处理程序。
if (!Page.IsPostBack)
{
using (SPSite site = new SPSite(SPContext.Current.Web.Url))
{
SPQuery query = new SPQuery();
query.Query = @"Query><OrderBy><FieldRef Name='Title' /></OrderBy><Query>";
query.ViewAttributes = "<FieldRef Name='Title' />";
query.ViewFields = string.Concat(
"<FieldRef Name='Title' />",
"<FieldRef Name='Status' />",
"<FieldRef Name='Severity' />",
"<FieldRef Name='Comment' />");
query.ViewFieldsOnly = true;
showGrid = new GridView();
this.Controls.Add(showGrid);
SPList list = SPContext.Current.Site.RootWeb.Lists["Ticket List"];
DataTable dt = new DataTable();
ButtonField approveBtn = new ButtonField();
approveBtn.ButtonType = ButtonType.Button;
approveBtn.CommandName = "Update";
approveBtn.Text = "Approve";
showGrid.Columns.Add(approveBtn);
dt = list.Items.GetDataTable().Copy();
dt = list.GetItems(query).GetDataTable();
showGrid.DataSource = dt;
showGrid.DataBind();
showGrid.RowCommand += new GridViewCommandEventHandler(inventoryGridView_RowCommand);
}
}
事件处理程序
if (e.CommandName == "Update")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = showGrid.Rows[index];
using (SPSite site = new SPSite(SPContext.Current.Web.Url))
{
using (SPWeb Web = site.OpenWeb())
{
Web.AllowUnsafeUpdates = true;
// Open List
SPList list = SPContext.Current.Site.RootWeb.Lists["Ticket List"];
SPListItem _listItem = list.Items[row.RowIndex];
_listItem["Status"] = "Approved";
_listItem.Update();
Web.AllowUnsafeUpdates = false;
}
}
}