FrenkyB FrenkyB - 20 days ago 5
C# Question

Formatting parameter as string in javascript function from .NET

My problem is how to properly format string in javascript function parameter list. Function call is created on the server, problem is with string single apostrophes.

Code (.NET, C#) (I want only element.cMEST_CDO2 in single quotes):

@"ng-click='DeleteElementFromSession(" + element.iMERC_KEY + "," + element.iACCO_KEY +
@",'" + element.cMEST_CDO2 + @"');'></i></div>";


This code is on the client visible like this (it throws error):

enter image description here

I would like to be like this:

enter image description here

EDIT:

What I've found out with help from Kevin is, that anything that is being rendered wiht HTML should be HTML encoded.

My solution - I've made whole string instead of single params and html encoded whole string:

string paramList = $"{element.iMERC_KEY},{element.iACCO_KEY},'{element.cMEST_CDO2}', $event";
paramList = WebUtility.HtmlEncode(paramList);


And then insert this string into parameter list:

@"ng-click='DeleteElementFromSession(" + paramList + ");'></i></div>";

Answer

What I've found out with help from Kevin is, that anything that is being rendered wiht HTML should be HTML encoded.

My solution - I've made whole string instead of single params and html encoded whole string:

string paramList = $"{element.iMERC_KEY},{element.iACCO_KEY},'{element.cMEST_CDO2}', $event";
paramList = WebUtility.HtmlEncode(paramList);

And then insert this string into parameter list:

 @"ng-click='DeleteElementFromSession(" + paramList + ");'></i></div>";