mcamara
mcamara

Reputation: 753

Encode text to JavaScript function

I'm trying to pass a text to my JavaScript function as bellow.

hplDetails.NavigateUrl = "JavaScript:GetSpecialEquipmentsDetails('" + ((SGViagens.Entities.SpecialEquipment)(e.Item.DataItem)).EquipmentCode + "','" + ((SGViagens.Entities.SpecialEquipment)(e.Item.DataItem)).EquipmentName + "')";

My second parameter contains any text with accents, special characters. But when I get in my JavaScript function, the text is mangled. Anyone have any tips for me?

Upvotes: 0

Views: 442

Answers (3)

Duncan Smart
Duncan Smart

Reputation: 32088

Having a utility function such as this in a class called, say StringUtil:

public static string JsEncode(string text)
{
    StringBuilder safe = new StringBuilder();
    foreach (char ch in text)
    {
        // Hex encode "\xFF"
        if (ch <= 127)
            safe.Append("\\x" + ((int)ch).ToString("x2"));
        // Unicode hex encode "\uFFFF"
        else
            safe.Append("\\u" + ((int)ch).ToString("x4"));
    }
    return safe.ToString();
}

... mean you can then encode the values as safe, JavaScript-encoded strings:

hplDetails.NavigateUrl = "JavaScript:GetSpecialEquipmentsDetails('" + StringUtil.JSEncode( ((SGViagens.Entities.SpecialEquipment)(e.Item.DataItem)).EquipmentCode + "','" + ((SGViagens.Entities.SpecialEquipment)(e.Item.DataItem)).EquipmentName ) + "')";

Upvotes: 1

Shadow Wizzard
Shadow Wizzard

Reputation: 66398

Instead of <asp:HyperLink> try having such thing:

<a id="hplDetails" runat="server">Text here</a>

Then assign its URL with such code:

hplDetails.Attributes["href"] = "URL here.....";

Hopefully this won't mess your special characters.

Upvotes: 1

Nick Butler
Nick Butler

Reputation: 24433

ASP.NET is encoding the NavigateUrl property.

Use decodeURI in your js function.

Upvotes: 1

Related Questions