I just need the client-side JavaScript to be able to send a string value to the ASP.NET server app. What's the common opinion on this process?
views:
78answers:
6A few ideas come to mind:
- URL itself. This requires the server to be able to parse the request to get that data out in an easy manner.
- Querystring. Appended to the querystring is likely the second easiest idea.
- Form data. Simulating a post request with the data in the post would be the most complicated but also the most secure in all likelihood.
Hello,
For passing variables content between pages ASP.NET gives us several choices. One choice is using QueryString property of Request Object. When surfing internet you should have seen weird internet address such as one below.
http://www.localhost.com/Webform1.aspx?firstName=Muse&secondName=VSExtensions
This html addresses use QueryString property to pass values between pages. In this address you send 3 information.
Webform.aspx this is the page your browser will go. firstName=Muse you send a firstName variable which is set to Muse secondName=VSExtensions you send a secondName variable which is set to VSExtensions
Put this code to the page page_load handler:
String firstName = Request.QueryString["firstName"]; String secondName = Request.QueryString["secondName"];
Regards...
I'm assuming you don't want to navigate away from the current page so, I would say to use an AJAX form post. Most javascript libraries have a simple method of doing so.
Your response can be a simple JSON object.
JavaScriptSerializer ser = new JavaScriptSerializer();
return ser.Serialize(new
{
@success = true,
@message = "some message"
});
add a hidden input on your webform, set its value client-side, and retrieve the value on postback.
Use jQuery to do all your client/server communications.
Post the data to an ASP.NET Generic Handler
var url = 'http://whatever.com/YourPage.ashx?data=' + escape("your data string");
$.post(url, {/* or send the data as a JSON object */}, function(response){
// do whatever with the response object
}, 'html'); // I'm assuming a html response here, but it could be anything..
then on the server create a Generic Handler class:
public class YourApplicationHandler : IHttpHandler
{
public void ProcessRequest (HttpContext context)
{
string data = Request.QueryString["data"];
// do your magic with the data
}
}
If you want a more specific answer, update the question with the specifics
I'd go with:
Client:
<script type="text/javascript">
function sendString(str){
(new Image).src = "/url.aspx?s=" + escape(str);
}
</script>
Server @ "/url.aspx" in Page_Load (C#):
string str = Request.QueryString["s"];
/* do stuff with str... */
// 204 means "NoContent"
Response.StatusCode = 204;
This method would probably win a code golf competition too. :-)