How to post params from javascript to asp.net?
-
03-07-2019 - |
Question
I have a javascript code which builds a link with 2 params.
Now, I know how to post these params using the address, but I don't want to use it.
I've tried using cookies for posting the params, but somehow I can't read them on the server side.
this is the client side code
document.cookie="name="+"value";
this is the server side reading code
string s = Response.Cookies[cookieName].Value;
Can you hep me out?
Solution
Create a mini form (not an asp.NET web form, just a simple one) with two input type hidden fields named as your parameters. After that create a link or button an tie the onclick event of it to a javascript function (example: onclick="javascript:postIt();").
Then when user clicks the button or the link the function will replace the value of those parameter something like:
document.miniform.parameter1.value = yourvalue1;
document.miniform.parameter1.value = yourvalue2;
document.miniform.submit();
To get the parameters back into code use Request.form("parameter1") and so on...
OTHER TIPS
You can use an Ajax Request to post your data to an ASP.NET form.
To post data to any page, you HAVE TO use the path to that page. As for your problem with setting the cookies, they can only be used by a page in the same domain.
Are you doing an HTTP Post? You could post these values inside a form field. I'd use a hidden input field. You can add one in your markup or add one via the javascript.
Your other option is to use some sort of Ajax and pass JSON or XML in the body of the post.
Cookies are meant to save data client side accross pages and/or sessions.