我是telerik和javascript的新手。我有一个链接按钮。单击按钮我从服务器端有两个条件。根据我需要调用javascript。
Aspx代码:
<asp:LinkButton ID="TestLinkButton" runat="server" OnClick="Test_Click"
SkinID="SmallCommandItemTemplateLinkButton">Test</asp:LinkButton>
服务器端代码:
protected void Test_Click(object sender, EventArgs e)
{
if (a == 0)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "scriptsKey", "<script type=\"text/JavaScript\" language=\"javascript\">ShowAlert();</script>");
}
else
{
TestLinkButton.Attributes["onclick"] = String.Format("return ShowEditForm('{0}')", test);
}
}
此处无法找到TestLinkButton。如果我在按钮单击参数中使用GridItemEventArgs,那么它会给出错误,因为'testLinkButton_click'匹配委托'System.Eventhandler'没有重载。
答案 0 :(得分:1)
可以从sender
事件处理程序的Test_Click
参数中检索LinkButton,并且可以将Javascript代码附加到其OnClientClick
属性:
LinkButton lnkButton = sender as LinkButton;
lnkButton.OnClientClick = String.Format("return ShowEditForm('{0}')", test);
答案 1 :(得分:0)
我可能错了,但我认为您正在寻找一种方法将javascript onclick
附加到GridView中的LinkButton
。您似乎是在LinkButton的服务器OnClick
上执行此操作,但这将需要往返于服务器(PostBack)。
您可以在GridView的OnItemDataBound
事件中执行相同的操作。您需要将OnItemDataBound
添加到GridView。
<telerik:RadGrid ID="RadGrid1" runat="server" OnItemDataBound="RadGrid1_ItemDataBound" >
背后的代码
protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
{
//check if the item is a GridDataItem
if (e.Item is GridDataItem)
{
//if 'a' needs to come from the dataset that is bound to the gridview, you can do this
GridDataItem item = (GridDataItem)e.Item;
string a = Convert.ToInt32(item["ID"].Text);
//or another grid value
string b = item["name"].Text;
//find the linkbutton with findcontrol and cast it back to one
LinkButton linkbutton= e.Item.FindControl("TestLinkButton") as LinkButton;
if (a == 0)
{
//attach the OnClientClick click function
linkbutton.OnClientClick = string.Format("ShowDeleteForm('{0}'); return false;", test2);
}
else
{
//attach the OnClientClick click function
linkbutton.OnClientClick = string.Format("ShowEditForm('{0}'); return false;", test);
}
}
}