如何检查在页面LinkButton
中单击了哪个Page_Load
。这是为了避免调用服务,以便它只执行其事件中存在的内容。
6 回答
唯一应该在您的系统中运行的Page_Load
是您希望在每次请求时始终发生的代码,或者将您只想运行一次的代码包含在回发检查中。例如:
protected void Page_Load(object sender, EventArgs e)
{
// Put the all code you need to run with EVERY request here
// Then add a post back check for any code you want to ONLY run on the very
// first request to the page.
if (!IsPostBack)
{
// Code you only want to run the first time. Usually setup code to initalize
// DropDownLists, Grids or pre populate a form, etc...
}
}
您的LinkButton
代码应该在点击处理程序中完全独立:
protected void yourLinkButton_Click(object sender, EventArgs e)
{
// code you want to execute when your button is clicked. This will run AFTER
// the Page_Load has finished.
}
现在,如果您在LinkButton
a或某种需要绑定来填充它的控件中使用,那么您可能需要实现一个事件处理程序来确定哪个被按下。您还可以将数据绑定到它的GridView
Repeater
RowCommand
LinkButton
CommandArgument
属性,以将一些唯一的行特定数据传递给偶数处理程序。
如果你有一堆LinkButton
s 都使用完全相同的处理程序,最坏的情况是转换sender
然后比较ID
值。
protected void yourLinkButton_Click(object sender, EventArgs e)
{
LinkButton btn = (LinkButton)(sender);
if (btn.ID.Equals("Some control name you want to compare"))
{
// do something
}
}
如果我对您的问题不满意,请发表评论,我会尽力解决。
编辑:根据您的评论,由于其他一些限制,您必须知道Button
它属于哪个。Page_Load
好吧,没有干净的方法可以做到,Page_Load
但可以做到。您将需要检查Request.Form
键并检查特定的按钮名称(只有Button
被单击的应该包含在键中)。例如:
if (Request.Form.AllKeys.Contains("yourButton1"))
{
// then do something based on yourButton1
}
else if (Request.Form.AllKeys.Contains("yourButton2"))
{
// then do something based on yourButton2
}
// etc...
我不认为这是绕过它的任何其他干净的方法。如果框架包含导致回发的控件之一,那就太好了sender
属性中包含导致回发的控件,那就太好了。
另一个编辑:这完全让我忘记了。上面的编辑是你需要做的,Button
因为它没有填充__EVENTTARGET
。由于您使用的是 aLinkButton
您可以使用以下内容来获取导致回发的控件:
string controlNameThatCausedPostBack = Request.Form["__EVENTTARGET"];
我已经用 a 测试了LinkButton
它,它确实按预期工作。
希望最终解决您的问题:)
我曾经不得不这样做,因为在事件处理程序中为时已晚。您可以使用 javascript 编写被点击到隐藏字段的按钮的 ID。比您可以在 Page_Load 中检索它。如果我没记错的话,另一种方法是查看 _EVENTTARGET 隐藏字段,已经有一段时间了。
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack && Request.Form["__EVENTTARGET"] == LinkButton1.UniqueID)
{
// LinkButton1 was clicked
}
}
您还可以声明一个 LinkButton(或 Control,或其他)类型的变量,并让按钮在 click 事件中使用对其自身的引用来更新它,然后检查 Load 处的值。
你的意思是当页面上的其他回发事件被触发时,你只是试图阻止 Page_Load 代码被执行?如果是这种情况,请将其包装在:
if (!IsPostBack)
(恕我直言,这有点像 WebForms 事件模型所必需的,但它就是这样。)
还是我误解了你的问题?
至于识别特定的 LinkButton,可以使用 CommandName 参数:
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.linkbutton.commandname.aspx
单独的处理程序是这里的方法,但您可以为每个按钮赋予一个独特的ItemCommand
属性,并根据需要过滤这些属性。