Arturo Pérez Arturo Pérez - 1 year ago 94
ASP.NET (C#) Question

Simple comma in session value ASP.NET

I have the next code and works fine:

var nombreregion = '<%= Session["regionNombre"]%>';

But if the value has a simple comma (') ocurrs the next error:

var nombreregion = 'LIBERTADOR GRAL B.O'HIGGINS';

The value is truncated...

How can i prevent this error?

Win Win
Answer Source

Session["regionNombre"] runs at server-side. So, you want to use String.Replace method to sanitize the data.

<script type="text/javascript">
    var nombreregion = 
        '<%= ((string)(Session["regionNombre"] ?? "")).Replace("'", "\\'") %>';
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download