在第二次回发后触发带有附加c#字符串的JS函数
本文关键字:字符串 JS 函数 第二次 | 更新日期: 2023-09-27 18:00:51
我有这个asp按钮:
<asp:Button ID="btnConfirm" runat="server" OnClick = "OnConfirm" Text = "Raise Confirm" />
我在后面有这个c#代码
public void OnConfirm(object sender, EventArgs e)
{
string eventIDel = "anyStringGivenAtRunTime";
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "DeleteUserChosenEvent", "confirmDeletion('" + eventIDel + "');", true);
string confirmValue = confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes")
{
// Do something like
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('You clicked YES!');", true);
}
else
{
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('You clicked NO!');", true);
}
}
我在代码中触发了这个JS函数。。。
"触发器"背后的代码:
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "JumpToBottom", "confirmDeletion('" + eventIDel + "');", true);" :
JS函数:
function confirmDeletion(str) {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm("Do you want to delete Event: " + str + " ?")) {
confirm_value.value = "Yes";
} else {
confirm_value.value = "No";
}
document.forms[0].appendChild(confirm_value);
如果我使用这样的语法,只有在第二次点击后,事件才会正常工作:
this.btnConfirm.Attributes.Add("onclick", "confirmDeletion('" + eventIDel + "');");
但是,如果我使用与原始语法类似的语法,它以NULL开头,而不要求确认,之后它将在确认上存储用户决定,并在用户下次按下按钮时使用它。
请帮忙,谢谢大家。
经过大量研究,我明白如果我从代码后面调用JS函数,页面周期总是会把它放在最后。对我来说,理想的方法是调用ASP按钮上的JS函数,默认情况下它将首先触发。ASP按钮
<asp:Button ID="BtnDelete" runat="server" Text="Delete" onclick="btnDelete_Click" class="buttons" Visible="true" disabled="disabled" OnClientClick="if (!deleteRow()) return false;" />
然后在JS函数中,我会提取整个网格视图,在我的情况下,每一行都通过单选按钮选择来识别,然后提取我想要的单元格的文本,就像这个
function deleteRow() {
// Get Gridview
var gridView = document.getElementById("<%= GridView1.ClientID %>");
// Loop through the Gridview
for (var i = 1; i < gridView.rows.length; i++) {
// Get the radio button of each row in the gridview and see if its checked
if (gridView.rows[i].cells[0].getElementsByTagName("INPUT")[0].checked == true)
// Get Event ID value from 1st cell of rowReturn Answer
return confirm("Are you sure you want to delete Event ID: " + gridView.rows[i].cells[1].innerText + "?");
}
}
之后,返回将显示true所有false,按钮将使用以下逻辑进行处理
OnClientClick="if (!deleteRow()) return false;"
这意味着,如果用户选择"是",它将转到负责删除的C#方法!!!
万岁!!!