ASP.NET quote character encoding causes problems when setting a control's property

馋奶兔 提交于 2019-12-20 03:19:47

问题


I have an ASP.NET web application and at a certain point I do this:

mycontrol.stringparameterforjscript = "document.getElementById('" + myotherparam + "').value = 'Hello'";

The problem is that this thing does not work. As you can see this sets a javascript in some event of some tag. Well when the page is redered the problem is that my parameter look like this:

<textarea onfocus="document.getElementById(&#39;myvalue&#39;).value = &#39;Hello&#39;"></textarea>

I must precise that this textbox I'm trying to set is located inside a InsertItemTemplate of a ListView and it is not so easy to intialize. For this reason I inserted my initialization code that you see inside the load event handler of my textbox. I can say you one thing: If this code referred to a text box located freely in the page and I called this piece of code from the load event handler of the page, this would work well. But I do not know how to do in this particular case.

I'm also considering the possibility to create a webcntrol to handle such a problem. I don't really know what's the best practice in this case.


回答1:


I think you might need the @ on both string literals in your assignment, and remove the slashes:

mycontrol.stringparameterforjscript = @"document.getElementById('" + myotherparam + @"').value = 'Hello'";

EDIT

How I did it:

On the .aspx:

<asp:Textbox ID="tbTest" runat="server" TextMode="MultiLine" />

In the code:

protected void Page_Load(object sender, EventArgs e)
{
    string myotherparam = "paramval";
    tbTest.Attributes.Add("onfocus", @"document.getElementById('" + myotherparam + @"').value = 'Hello'");
}

Resultant output:

<textarea name="tbTest" rows="2" cols="20" id="tbTest" onfocus="document.getElementById('paramval').value = 'Hello'"></textarea>



回答2:


OK, I finally managed it. HTML Encoded strings recognized by the javascript engine, how's it possible? As you will see there is nothing to worry about in what happens.



来源:https://stackoverflow.com/questions/4411419/asp-net-quote-character-encoding-causes-problems-when-setting-a-controls-proper

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!