问题
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('myvalue').value = 'Hello'"></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