Reputation: 12447
I want to send a string I built using the StringBuilder
to the HTML page, which then I want to use in my JavaScript code.
Right now here's what I am doing:
On the client side:
<div id="data">
<asp:Literal ID="Literal1" runat="server"></asp:Literal>
</div>
In my JS block:
var data = $("#data").html();
In the code behind:
Literal1.Text = strXml.ToString();
The thing is, this data can be seen by going through the source of the data
div, which I dont want to allow.
I want this string as soon as the page loads, so I guess making an AJAX call after the page has loaded to the server is out of the way.
Any smoother way ?
It's a .NET rookie here.. :)
Upvotes: 0
Views: 1770
Reputation: 700402
There are some other ways of putting the content in the page, like hidden fields and data islands, but they are all still as visible in the page source.
You could obfuscate the data to make it harder to read, but it's still easy to pause the script where it uses the data after unscrambling it, and the data is still visible.
So, if you want the data available immediately when the page loads, it needs to be included in the page, and it will be possible for the user to see it.
Upvotes: 1
Reputation: 86749
Your approach looks fine to me, the alternative is to use a hidden input
:
<input type="hidden" runat="server" id="data" />
In code behind:
this.data.Value = strXml;
In JavaScript:
var data = $("#data").val();
Like the div
however you will be able to see the value submitted in the source for the page, however if I understand your requirement correctly this is unavoidable by the very requirement of being able to access this data in JavaScript - the best you can obfuscate this data, however someone sufficiently determined enough will be able to inspect and see this data whatever method you choose.
If the data is not sensitive then go ahead and place it in a hidden field on the form and don't worry about it. If the data is sensitive and the user isn't meant to see it then you should probably refactor your page so that the processing is done on the server and only the parts that are meant to be visible are ever present in the browser.
Upvotes: 2
Reputation: 3883
you can save your string in an HiddenField
then read its value using javascript something like this
<asp:HiddenField runat="server" ID="MyHidden">
in code behind
MyHidden.Value = strXml.ToString();
javascript
var data = $('#<%=MyHidden.ClientID%>').val();
or you can define strXml
as protected
variable and use it inside .aspx
like that
public class _MyPage:Page
{
Protected String strXml;
private void Page_Load(Object sender,EventArgs e)
{
StringBuilder mystrBuilder = new StringBuilder();
//append some text to mystrBuilder
strXml = mystrBuilder.ToString();
}
}
javascript code will like this
var data = '<%=strXml%>';
Upvotes: 3