C# 如何以编程方式更改 OnClientClick 事件并调用它?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1875233/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to programmatically change the OnClientClick event and call it?
提问by Xaisoft
I have a ListView that contains playlists. If the user wants to edit an album, they click the edit link and it allows them to remove or add songs to the playlist. If the user wants to Save a new playlist while keeping the original one, the would click a Save As Button. Here is what should happen:
我有一个包含播放列表的 ListView。如果用户想要编辑专辑,他们点击编辑链接,它允许他们删除或添加歌曲到播放列表。如果用户想要在保留原始播放列表的同时保存新播放列表,则可以单击另存为按钮。这是应该发生的事情:
If the user clicks Save As and they have not changed the name, I want to display an alert telling them they must change the name.
如果用户单击另存为并且他们没有更改名称,我想显示一个警报,告诉他们必须更改名称。
If the user clicks the Save As and they have changed the name, I want to display an a confirmation that they actually want to save it.
如果用户单击“另存为”并且他们更改了名称,我想显示他们确实想要保存它的确认。
Currently, what is happening is that if I put something like the following in my code behind, the script does not register until the second click and whatever script was registered stays registered meaning that if I end up changing the name and the alert script was registered before, it will display the alert instead of the confirmation. Here is the code:
目前,正在发生的事情是,如果我在我的代码后面放了类似下面的内容,脚本直到第二次点击才会注册,并且注册的任何脚本都会保持注册,这意味着如果我最终更改了名称并且警报脚本已注册之前,它将显示警报而不是确认。这是代码:
if (newname == oldname)
{
btnSaveAs.OnClientClick =
"javascript:alert('Save As requires you to change the name of the playlist. Please
change the name and try again.');";
}
else
{
btnSaveAs.OnClientClick = "javascript:confirm('Are you sure you want to save the
playlist" + newname + "?');";
}
I also tried adding the return false so it would not do a postback, but if I do that, then it does not doesn't actually do anything when I click OK on the confirmation.
我还尝试添加 return false 以便它不会进行回发,但是如果我这样做,那么当我在确认上单击“确定”时它实际上不会执行任何操作。
采纳答案by KP.
What SLaks said is correct, you're misunderstanding the page lifecycle. The javascript code needs to be in place on the page beforeyou click Save As. In your example as described, the user makes changes to the title/name and clicks Save As, after which the javascript code is applied to the button. The second time they click Save As, the validation results from the previous example pop up.
SLaks 说的是正确的,您误解了页面生命周期。在单击“另存为”之前,需要在页面上放置 javascript 代码。在您描述的示例中,用户更改标题/名称并单击“另存为”,然后将 javascript 代码应用于按钮。他们第二次单击“另存为”时,会弹出上一示例的验证结果。
Option 1: Use a validator control
选项 1:使用验证器控件
The simplest way to solve this is to use a RegularExpressionValidator control to compare the values.
解决此问题的最简单方法是使用 RegularExpressionValidator 控件来比较值。
Markup snippet:
标记片段:
<asp:Label ID="lblName" runat="server" Text="Name: " />
<asp:TextBox ID="txtName" runat="server" />
<asp:RegularExpressionvalidator ID="valName" runat="server" ControlToValidate="txtName" ErrorMessage="You must change the name before saving" Display="Dynamic" />
<asp:Button ID="btnSaveAs" runat="server" OnClick="btnSaveAs_Click" Text="Save As" CausesValidation="True" />
In your code-behind once the form fields (album name, etc.) are bound, run this:
在表单字段(专辑名称等)绑定后的代码隐藏中,运行以下命令:
valName.ValidationExpression = string.Format("[^{0}]", Regex.Escape(lblName.Text));
The above regular expression will be valid for any input except what was there to begin with. If the user changes the text for the album name, the save button will validate correctly. If they do not, the validator will kick in and display a message on the page saying they have to change it.
上面的正则表达式对任何输入都有效,除了开头的内容。如果用户更改专辑名称的文本,保存按钮将正确验证。如果他们不这样做,验证器将启动并在页面上显示一条消息,说他们必须更改它。
Then handle the OnClick
event of the save button only for saving the values, because it will only fire if the page was validated:
然后处理OnClick
保存按钮的事件仅用于保存值,因为它只会在页面被验证时触发:
protected void btnSaveAs_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
//do you save actions as needed
}
}
You can also still use your confirm box as you wanted, by doing:
您还可以通过执行以下操作,根据需要使用确认框:
protected void Page_Load(object sender, EventArgs e)
{
btnSave.OnClientClick = "return confirm('Are you sure you wish to change the name?');";
}
The above should work just fine. An alternate approach is listed below:
以上应该工作得很好。下面列出了另一种方法:
Option 2: Use a clientside validation function
选项 2:使用客户端验证功能
If you wanted to do the validation completely client side, you could but it will be far more complicated. What you'd need to do, is register a completely clientside validation function.
如果您想完全在客户端进行验证,您可以,但它会复杂得多。您需要做的是注册一个完整的客户端验证功能。
In your code behind during Page_PreRender:
在 Page_PreRender 期间后面的代码中:
protected void Page_PreRender(object sender, EventArgs e)
{
//define the script
string script = @"
function validateAlbumName(oldName, textBoxId) {
//get the textbox and its new name
var newName = document.GetElementById(textBoxId).value;
//compare the values
if (newName === oldName) {
//if the name hasn't changed,
alert('You must change the name of the album');
return false;
}
return confirm ('Are you sure you want to save the playlist ' + newName);
}
";
//register the client script, so that it is available during the first page render
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "SaveAsValidation", script);
//add the on client click event, which will validate the form fields on click the first time.
btnSaveAs.OnClickClick = string.Format("return validateAlbumName('{0}','{1}');", txtAlbumName.Text, txtAlbumName.ClientID);
}
Hope this helps. There are likely some syntax errors in the above as I just threw it together quickly..
希望这可以帮助。上面可能有一些语法错误,因为我只是快速地把它放在一起..
回答by SLaks
The OnClientClick
property is a Javascript string, not a URI. Therefore, you should not begin it with javascript:
.
该OnClientClick
属性是一个 Javascript 字符串,而不是一个 URI。因此,您不应以javascript:
.
To handle the confirm
correctly, write OnClientClick = "return confirm('Are you sure?');";
为了confirm
正确处理,写OnClientClick = "return confirm('Are you sure?');";
Also, you're misunderstanding the ASP.Net page model.
此外,您误解了 ASP.Net 页面模型。
Your C# code-behind event handler only runs afterthe user clicks the button and afterthe OnClientClick
callback. You need to write all of that in Javascript and call it in OnClientClick
.
你的C#代码隐藏事件处理程序只运行后,用户点击该按钮,之后的OnClientClick
回调。您需要在 Javascript 中编写所有这些并在OnClientClick
.