Home > Software engineering >  Unexpected identifier when concatenate string from codebehind on ASP.NET
Unexpected identifier when concatenate string from codebehind on ASP.NET

Time:11-03

This is a very small bug that I have been trying figure out for couple hours.

Considering this code behind

using System;

public partial class Controls_DashboardGraph : InboundOutboundControl
{
    public string GraphTitle
    {
        get
        {
            if (2>1) //To simply the logic, it will always meets this condition
            {
                return "The World";
            }
            else
            {
                return "All Cocoms";
            }
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        //Somelogic here
    }
}

It has a GraphTitle variable in it.

And I am trying to use the value the front page to perform an online string concatenation

<%@ control language="C#" autoeventwireup="true" codefile="DashboardGraph.ascx.cs" inherits="Controls_DashboardGraph" %>

<script type="text/javascript">
    var title = <%= this.GraphTitle%>;
    var isInBound = "true";
    <%
    if (3>2) //To minimize the code, simply the logic here
    {
    %>
        path = `Services/ChartData.asmx/RetrieveChart?title=${title}&inbound=${isInBound}`;
    <%
    }
    else
    {
    %>
        isInBound = "false";
        path = `Services/ChartData.asmx/RetrieveChart?title=${title}&inbound=${isInBound}`;
    <%
    }
    %>
    $.ajax({
        type: "GET",
        url: path,
        success: function (data) {
             //DoSomething
        }
    });
</script>

I am trying to concatenate the string to get a path so I can use in ajax. However, when I do this, I got

'Uncaught SyntaxError: Unexpected identifier 'World'

on line var title = <%= this.GraphTitle%>;;

What I have tried:

1: I thought it is because of the space in the string. However, when I changed the return value to "TheWorld", I got

Uncaught ReferenceError: TheWorld is not defined

2: Different bee-stings I have tried:<%# %>, didn't work either.

What I need help with: I know this is a very trivial bug, but I have been bugged by it for a while. What is wrong here? why does this simply string concatenation throwing erros?

CodePudding user response:

Change this:

var title = <%= this.GraphTitle%>;

to this:

var title = "<%= Regex.Escape( this.GraphTitle ) %>";
  • Note two things:
    1. The outer double-quotes ".
    2. The use of Regex.Escape as a poor-man's substitute to convert in-memory .NET String chars to an escaped JavaScript string, as JavaScript and .NET regex share many escape-sequences (though this approach isn't perfect, it works in a pinch).
      • So if GraphTitle contains a double-quote char then it will be rendered as a JS escaped quote, thus your JS <script> element won't get garbled.
  • Related