How should I send a JavaScript variable to (ASP.NET code behind) C# without using an <input type="hidden" /> field? In browser inspectors the hidden field and its value are visible and editable.
-
1Please, share some codevaqifrv– vaqifrv2016-08-03 14:31:33 +00:00Commented Aug 3, 2016 at 14:31
3 Answers
You can use AJAX methods
A good tutorial: http://www.brainbell.com/tutorials/ASP/A_Web_Service_In_ASP.NET.html
For example, code behind:
[WebMethod]
public static bool UpdateLocation(string lat)
{
try
{
//Your code
}
catch (Exception ex)
{
throw;
}
}
Example Javascript Code:
$.ajax({
type: "POST",
url: "/MyPage.aspx/UpdateLocation",
data: "{lat:'1313.23232'}",
contentType: "application/json; charset=utf-8",
dataType: "json"
});
3 Comments
web service?data doesn't need "".. it just needs to be data: { 'lat': 1313.23232 }Two things:
First, as @AnibalDíaz said, you should probably be performing this operation via AJAX instead of in a form. if you don't want to have an <input type="hidden" /> tag on your page.
Second, however, if your concern is that the user can see the value of that field, you have much bigger problems. In current browser inspectors there's generally a Network tab where you can view all HTTP requests from the page. Most people who are looking for that data in the HTML will also know that they can trivially see the data in the HTTP request itself through the network tab, and in fact they may go there first instead of examining the form. If you're worried about them changing the data, many browsers' Network tools also allow you to modify a request and send it again, so they will also be able to easily send another request with a different value for that field.
There are ways to make this more difficult, but ultimately, nothing on a web page is private. When you send the user a webpage, you are sending them all your JavaScript code as well. A malicious user can always modify that code and change its behavior. What this means is that you should never rely on browser for security. If you don't want the user to be able to see or modify some data, don't send that data to the user.
You probably need to rethink your architecture a little. I don't know much about C# or ASP.NET, but if you can maintain per-user sessions on the server and store data associated with that user on the server, that's the way to go. The user can't get to your data if it's stored on the server and never sent to the browser.