C# 在onclientclick中将变量传递给javascript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12850327/
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
Passing variables to javascript in onclientclick
提问by Christian Bekker
Okay, i think i've tried 3-4 methods here from stackoverflow, but none seems to work.
好的,我想我已经在 stackoverflow 中尝试了 3-4 种方法,但似乎都不起作用。
I've got:
我有:
OnClientClick='<%# Eval("albumName", "doConfirm(\"delete\", \"{0}\");").ToString() %>'
but in html it renders as:
但在 html 中它呈现为:
onclick="doConfirm("delete", "Test");"
Also tried making a method to call:
还尝试制作一个方法来调用:
public string CreateConfirmation(String action, String item) {
return String.Format(@"return confirm('Sikker p? du vil {0}: {1}');", action, item);
}
With this:
有了这个:
OnClientClick='<%# CreateConfirmation("delete", (string)Eval(albumName)) %>'
But gives me exact same problem.... So im pretty lost?
但是给了我完全相同的问题......所以我很迷茫?
采纳答案by pete
I apologize in advance for such a long answer, but I wanted to be thorough.
对于这么长的答案,我提前道歉,但我想彻底。
This is apparently a "security" feature in .Net 4.0 (and higher). You can read more about it at:
这显然是 .Net 4.0(及更高版本)中的“安全”功能。您可以在以下位置阅读更多信息:
- http://avinashsing.sunkur.com/2010/10/29/asp-net-html-encoding-attributes-in-server-controls/
- http://forums.asp.net/p/1554455/3818604.aspx
- Stop the tag builder escaping single quotes ASP.NET MVC 2
- http://avinashsing.sunkur.com/2010/10/29/asp-net-html-encoding-attributes-in-server-controls/
- http://forums.asp.net/p/1554455/3818604.aspx
- 停止标签生成器转义单引号 ASP.NET MVC 2
All of the above links also recommend declaring a public class to override the behavior:
以上所有链接还建议声明一个公共类来覆盖行为:
public class HtmlAttributeNoEncoding : System.Web.Util.HttpEncoder
{
protected override void HtmlAttributeEncode(string value, System.IO.TextWriter output)
{
output.Write(value);
}
}
and then adding this to the <system.web>element in your web.config:
然后将其添加到<system.web>web.config 中的元素:
<httpRuntime encoderType="HtmlAttributeNoEncoding"/>
This definitely fixes the rendering problem, so that quotes and apostrophes render as "and '(as expected).
这绝对解决了呈现问题,因此引号和撇号呈现为"和'(如预期的那样)。
That said, I tested your problem with the following:
也就是说,我用以下方法测试了您的问题:
<script type="text/javascript">
var doConfirm = function (action, item) {
alert('Sikker p? du vil ' + action + ': ' + item);
return false;
};
</script>
<p>Some "arbitrary" text. <asp:Button ID="Button3" runat="server" Text="Button" OnClientClick="doConfirm('delete', 'myalbum');" /></p>
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick='<%# Eval("albumName", "doConfirm(\"delete\", \"{0}\");").ToString() %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Album Name" DataField="albumName" />
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="Button2" runat="server" Text="Button" OnClientClick='<%# CreateConfirmation("delete", (string)Eval("albumName")) %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and in the code-behind:
并在代码隐藏中:
public partial class _Default : System.Web.UI.Page
{
public string CreateConfirmation(String action, String item)
{
return String.Format(@"return doConfirm('{0}', '{1}');", action, item);
}
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
DataColumn dc = new DataColumn("albumName", typeof(string));
DataRow dr = null;
dt.Columns.Add(dc);
dr = dt.NewRow();
dr["albumName"] = "Zen Arcade";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["albumName"] = "New Day Rising";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["albumName"] = "Candy Apple Grey";
dt.Rows.Add(dr);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
I was able to duplicate your rendering problem:
我能够复制您的渲染问题:
<p>Some "arbitrary" text.
<input type="submit" onclick="doConfirm('delete', 'myalbum');" value="Button" name="ctl00$MainContent$Button3" id="MainContent_Button3" />
</p>
<div>
<table cellspacing="0" rules="all" border="1" id="MainContent_GridView1"
style="border-collapse:collapse;">
<tr>
<th scope="col"> </th>
<th scope="col">Album Name</th>
<th scope="col"> </th>
<th scope="col">albumName</th>
</tr>
<tr>
<td>
<input type="submit" onclick="doConfirm("delete", "Zen Arcade");" value="Button" name="ctl00$MainContent$GridView1$ctl02$Button1" id="MainContent_GridView1_Button1_0" />
</td>
<td>Zen Arcade</td>
<td>
<input type="submit" onclick="return doConfirm('delete', 'Zen Arcade');" value="Button" name="ctl00$MainContent$GridView1$ctl02$Button2" id="MainContent_GridView1_Button2_0" />
</td>
<td>Zen Arcade</td>
</tr>
<tr>
<td>
<input type="submit" onclick="doConfirm("delete", "New Day Rising");" value="Button" name="ctl00$MainContent$GridView1$ctl03$Button1" id="MainContent_GridView1_Button1_1" />
</td>
<td>New Day Rising</td>
<td>
<input type="submit" onclick="return doConfirm('delete', 'New Day Rising');" value="Button" name="ctl00$MainContent$GridView1$ctl03$Button2" id="MainContent_GridView1_Button2_1" />
</td>
<td>New Day Rising</td>
</tr>
<tr>
<td>
<input type="submit" onclick="doConfirm("delete", "Candy Apple Grey");" value="Button" name="ctl00$MainContent$GridView1$ctl04$Button1" id="MainContent_GridView1_Button1_2" />
</td>
<td>Candy Apple Grey</td>
<td>
<input type="submit" onclick="return doConfirm('delete', 'Candy Apple Grey');" value="Button" name="ctl00$MainContent$GridView1$ctl04$Button2" id="MainContent_GridView1_Button2_2" />
</td>
<td>Candy Apple Grey</td>
</tr>
</table>
</div>
When any of the buttons were clicked, the JavaScript function ignored the HTML encoding, alerting me to:
当单击任何按钮时,JavaScript 函数会忽略 HTML 编码,提醒我:
Sikker p? du vil delete: Zen Arcade
so while it looks funky in the source, having quotes and apostrophes render as "and 'doesn't really appear to affect anything.
因此,虽然它在源代码中看起来很时髦,但将引号和撇号渲染为"并且'似乎并没有真正影响任何事情。
回答by Konstantin Dinev
Try the following:
请尝试以下操作:
<asp:Button OnClientClick="Delete(this);" Text='<%# Eval("albumName"); %>' />
JS:
JS:
function Delete(element) {
var value = element.value;
return confirm('Delete' + value + '?');
}
回答by Zo Has
Just attach the event server side inside rowDataBoundevent like, (you can replace linkbutton with Button)
只需将事件服务器端附加在rowDataBound事件中,例如(您可以用按钮替换链接按钮)
LinkButton myLinkButton=(LinkButton)e.row.FindControl("yourButtonName");
if(myLinkButton!=null)
{
myLinkButton.Attributes.Add("onclick","javascript:return confirm ('Are you sure you want to delete "+ DataBinder.Eval(e.row.DataItem, "YourDbField") + " ?');");
}
回答by Richard Teel
Even though this question is 5 years old, I wanted to follow up as I had the same issue with an ImageButton and was able to resolve it using a HiddenField.
尽管这个问题已经有 5 年的历史了,但我还是想跟进一下,因为我在 ImageButton 上遇到了同样的问题,并且能够使用 HiddenField 解决它。
Background: I have a Web User Control which I wanted to have a help button displayed if there was help available.
背景:我有一个 Web 用户控件,如果有可用的帮助,我想显示一个帮助按钮。
I added a HiddenField and an ImageButton to the User Control. I then created a property on the control so the developer may add help text.
我在用户控件中添加了一个 HiddenField 和一个 ImageButton。然后我在控件上创建了一个属性,以便开发人员可以添加帮助文本。
ASPX Page
ASPX 页面
<asp:HiddenField ID="hidHelpText" runat="server" />
<asp:ImageButton ID="imgHelp" runat="server" ImageUrl="~/images/help.png" Visible="False" />
Code Behind (CS File)
代码隐藏(CS 文件)
public string HelpText
{
get { return hidHelpText.Value; }
set { hidHelpText.Value = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
imgHelp.Visible = !string.IsNullOrEmpty(HelpText);
imgHelp.OnClientClick = string.Format("MsgBox({0}.value, MessageButtons.OK); return false;", hidHelpText.ClientID);
}
This gets around the issue as the text belongs to the hidden field instead of trying to include it within the JavaScript for the OnClientClick property.
这解决了这个问题,因为文本属于隐藏字段,而不是尝试将其包含在 OnClientClick 属性的 JavaScript 中。
BTW: I cannot copy and paste so this code may contain some typos but I believe it is correct. At least it points the way so you may be able to work around the issue.
顺便说一句:我无法复制和粘贴,所以这段代码可能包含一些错别字,但我相信它是正确的。至少它指明了方向,因此您可以解决该问题。

