Talha Talha - 1 month ago 6
ASP.NET (C#) Question

The value passed in onclick() attribute of dynamically generated anchor tag is ending with first space

have to pass two parameters in the onlclick() of anchor tag which is being generated from code behind(c#).if there is any space in the first parameter the onclick() is being closed with double quotes. It is not taking the complete value.

LiteralControl lc2 = new LiteralControl();
lc2.Text = String.Format("<a href='#' class='easyui-linkbutton' " + @"onclick=addTab(" + childMenus[j].MenuName.ToString() + "," + url + @")> " + @" Setting " + @" </a>");


screenshot of browser's inspect element :
enter image description here

the value of first parameter is "Exam and course setting" but it is ending after "Exam" at first space. It is assuming space as ending.

Answer

I've changed the controls in my lc2 string to use string variables to demonstrate how you can create the escaped html:

string MenuName = "Exam and course setting";
string url = "http://stackoverflow.com";

var lc2 = "<a href='#' class='easyui-linkbutton' " + @"onclick='addTab(""" + MenuName.ToString() + @""",""" + url + @""")'>" + @"Setting" + @"</a>";

which will generate the following:

<a href='#' class='easyui-linkbutton' onclick='addTab("Exam and course setting","http://stackoverflow.com")'>Setting</a>

Don't forget to HTMLEncode any text from the controls if they contain single or double quotes. You can replace with &#39; for ' and &#34; for ".