Skip to content Skip to sidebar Skip to footer

How To Properly Pass Eval To Javascript Function?

What is the proper way to pass an asp.net value into javascript? For instance, this line of code says I am missing a token..

To pass data to JavaScript, use custom [data-*] attributes and JSON.

ascx
<asp:ImageButtonrunat="server"ID="Button" />
ascx.cs
Button.Attributes["data-foo"] =
    new {
            bar = "baz",
            fizz = "buzz"
        }.ToJSON();
ToJSON extension method
publicstaticstringToJSON(thisobject source)
{
    var jss = new JavaScriptSerializer();
    return jss.Serialize(source);
}
Access in JS via jQuery:
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.

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.

Solution 2:

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. 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() %>');"/>

Solution 3:

Finally pulled it off with the following:

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

Solution 4:

Try replacing the '\' with an additional '"'

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

Post a Comment for "How To Properly Pass Eval To Javascript Function?"