简体   繁体   English

如何正确地将Eval传递给javascript函数?

[英]How to Properly pass Eval to javascript function?

What is the proper way to pass an asp.net value into javascript? 将asp.net值传递到javascript中的正确方法是什么? For instance, this line of code says I am missing a token.. 例如,这行代码说我缺少令牌。

<asp:ImageButton runat="server" ImageUrl="/ESDNET/Images/Icons/add.png" OnClientClick="return 'ShowNewNoteForm("<%# Eval("SuggestionID").ToString() %>");'/>

eval is evil . 评估是邪恶的 You don't need to build JavaScript with server side code, it's a good way to cause yourself to have a massive headache. 您不需要使用服务器端代码来构建JavaScript,这是使自己头痛的好方法。

To pass data to JavaScript, use custom [data-*] attributes and JSON . 要将数据传递给JavaScript,请使用自定义[data-*]属性JSON

ascx ascx
 <asp:ImageButton runat="server" ID="Button" /> 
ascx.cs ascx.cs
public static string ToJSON(this object source)
{
    var jss = new JavaScriptSerializer();
    return jss.Serialize(source);
}
ToJSON extension method ToJSON扩展方法
 public static string ToJSON(this object source) { var jss = new JavaScriptSerializer(); return jss.Serialize(source); } 
Access in JS via jQuery: 通过jQuery在JS中访问:
 var foo; foo = $('[data-foo]').data('foo'); console.log(foo.bar); //'baz' console.log(foo.fizz); //'buzz'; 

One of the most important things about this setup is that C# will correctly JSON and HTML encode the data (in that order), following that, the JavaScript api will correctly decode the HTML attribute, and jQuery will correctly parse the JSON object. 关于此设置的最重要的事情之一是C#将正确地对JSON和HTML编码数据(按该顺序),然​​后,JavaScript api将正确地解码HTML属性,而jQuery将正确地解析JSON对象。

What this means is that if you add special characters or encoded values to your C# object, you'll end up with those special characters or encoded values in your JavaScript object, without having to mess with anything to get it to work. 这意味着,如果在C#对象中添加特殊字符或编码值,则最终将在JavaScript对象中获得这些特殊字符或编码值,而无需进行任何操作即可使其正常工作。

Your quotes are wrong. 您的报价有误。 You should open and close the OnClientClick assignment with, double quotes, and anything inside your javascript code should be single quotes. 您应使用双引号打开和关闭OnClientClick分配,并且您的javascript代码中的任何内容都应为单引号。 Then, inside your breaking tags, you need to go back to double quotes. 然后,在中断标签内,您需要返回双引号。 This should work... 这应该工作...

<asp:ImageButton runat="server" ImageUrl="/ESDNET/Images/Icons/add.png" OnClientClick="return ShowNewNoteForm('<%# Eval("SuggestionID").ToString() %>');"/>

最终通过以下步骤将其拉开:

 <asp:ImageButton runat="server" ID="addNote" ImageUrl="/ESDNET/Images/Icons/add.png" OnClientClick='<%# String.Format("return ShowNewNoteForm(\"{0}\")", Eval("SuggestionID")) %>'/>

尝试将“ \\”替换为其他“”

 <asp:ImageButton runat="server" ID="addNote" ImageUrl="/ESDNET/Images/Icons/add.png" OnClientClick='<%# String.Format("return ShowNewNoteForm(""{0}"")", Eval("SuggestionID")) %>'/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM