I already found this on this website.
how to pass session variable in href
But what I want is vice versa. and I can't get it done..
I need some correct syntax..
is it ......
..../home.aspx?<%Session["egSession"]=1%>
or
..../home.aspx?=<%Session["egSession"]=1%>
or
..../home.aspx?<%=Session["egSession"]=1%>
But i believe all of the above are wrong.. coz none of them are working..
Tkz..
Session.Add("egSession", 1) will add 1 to the session cookie egSession.
You could also probably be sure it doesn't already exist by doing so:
Session.Remove("egSession");
Session.Add("egSession", 1);
To get the querystring value from the address you would (code behind do)
var value = Request["egSession"];
So that means you could do:
Session.Remove("egSession");
Session.Add("egSession", Request["egSession"]);
Hope that helps!
** UPDATE **
If you can't touch the .cs files, you can do this in the ASPX-file, by wrapping your code in <% ... code goes here ... %>
if the new session variable value is know, e.g. 1 in your sample setting it can be done anywhere
<% Session["egSession"]=1; %>
if you want to pass it through as a query parameter do this:
..../home.aspx?egSession=<%=Session["egSession"]%>
The point is, you need a name for the value, i.e. egSession but you may call it what ever you want.
However, if you alldready know the value you can simply do:
..../home.aspx?egSession=1
From what I am understanding you want something like this:
APage
Take Me home
Home.aspx.cs: the code behind page, in say the OnPageLoad Event
Session["egSession"] = Request.QueryString["egSession"];
Home.aspx
<div>Session: <% =Session["egSession"] %></div>
<div>Query String: <% = Request.QueryString["egSession"] %></div>
If you are trying to to it all in one I would try the following:
APage.aspx.cs
Create a public method (change the type of the input parameter if needed)
public string SessionMagic(object input)
{
Session["egSession"] = input;
return Session["egSession"].ToString();
}
APage.aspx
A Link
*UPDATE: *
If you can not update the .cs files you can add server side code in the aspx page, not great practice but it can be done. Encapsulate the code in script tags with the run a server attribute set. E.g.:
<script runat="server">
public string ServerSideFunction(string input)
{
Session["egSession"] = Request.QueryString["egSession"];
public string SessionMagic(object input)
{
Session["egSession"] = input;
return Session["egSession"].ToString();
}
}
</script>
you can use javascript with cookie to store the value that you want to set into Session.
eg:- url- url.apsx/egValue=1 read this url using javascript. Put the key and value into cookie.
Then you can read cookie value from server and put it into session.
hope it helps.
Related
Well, this is a bit weird i think to ask this question, because i am not sure if that's the place to ask that.
OK, into the question..
I have this code
<script>
var session = "<%= Session["User"]%>";
</script>
So, i was thinking, is that safe? let me tell you what i mean..
I have a web api which you can get the name, last name, age and everything about the user with his Session, can i send this web api this session and use it?
Is that a safe thing to do ? in matter of securiy? if not, is there any better way?
EDIT 1:
What am i trying to aaccomplish? simple, i will store the UserId in the session, the UserId will Guid, when the user is loogin in the javascript can send post to an API server to get info, the API will send the UserId from the session.
Is That ok?
Workflow that you describe looks fine. For me it seems safe to use some ID to get more information about some user, especially if this is supposed to be an API, at least, Facebook API uses such principle not being afraid of some hackers :)
My main concern here is the coding style when you try to mix code and view which is not good. If you really need to share some information between client and server sides then I would go with one of these options.
Option # 1 - Cookies
What is the difference between a Session and a Cookie?
You can keep some simple information in a cookie and get it this way :
Client : $.cookie('ID')
Server : Response.Cookies["ID"]
In this case there is no need to put in a mess your client side JS with C# code and cookies will be saved on users PC which means that nobody will see them except him.
Option # 2 - Templates
Server : put all needed information into hidden form or ViewState
Client : take information from hidden form using HTML selectors
Straight answer :
In general, if you worry only about safety then it is fine to use this code, it should not break security of your site.
Although, personally I do not like this approach because :
you will mix code and view, MVC was created to split them
it is not clear where exactly in your view you will put this code and thus it is not clear how you are going to check that this variable was initialized
it may happen that you will put there some value that will break JS syntax and will cause JS error
In my personal opinion, I would replace it with one of the mentioned options.
Option 1 - MVC + JQuery + Cookie Example
public ActionResult Index()
{
string demo = Request.QueryString["MyNameSpace.ID"]; // get value from client
Response.Cookies["MyNameSpace.ID"].Value = "server"; // change value in response
return View();
}
Then in your JS file :
$(document).ready(function() { // make sure server rendered page
var ID = $.cookie('MyNameSpace.ID'); // get cookie value from server
$.cookie('MyNameSpace.ID', 'client'); // update, on the next request server will get it
});
Option 2 - MVC + JQuery + Templates Example
public class OptionsModel // View Model
{
public string ID { get; set; }
public string User { get; set; }
}
public ActionResult Index() // Controller
{
OptionsModel options = new OptionsModel();
options.ID = "server";
return View(options);
}
Your view :
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage<OptionsModel>" %>
<%=Html.HiddenFor(m => Model.ID, new { #class = "MyNameSpace:ID" })%>
<%=Html.HiddenFor(m => Model.User, new { #class = "MyNameSpace:User" })%>
Then in your JS file :
$(document).ready(function() { // make sure server rendered page
var options = $('[class^=MyNameSpace]') // get values from hidden fields
options[0] = 'client'; // update data
$.ajax({ data : options }); // create handler to send data back to server
});
Examples for Web Forms do not differ significantly.
The code you have posted will be rendered on the page as so when it hits the client (assuming you are using ASP.NET
<script>
var session = "John Smith";
</script>
This is due to the use of the server side scripting tags <%= %> (https://technet.microsoft.com/en-us/library/cc961121.aspx)
As a note its probably not the best thing in the world to fully expose the session to javascript if that is your intention. At the end of the day it depends what you are storing in there and using it for (but ASP.NET will also use it for certain things) but exposing it just opens another area for someone to attack.
http://www.owasp.org is a great place to learn more about securing your website.
In MVC, the default views for a controller allow one to reach the edit page via selecting an item in an index and using that id to reach the specific edit page.
In this MVC edit page, I have a javascript that reacts to a change in a dropdown. The dropdown represents a subset of the potential id's available from the index page, and in general, someone will choose a different one than the currently displayed one.
The postback to the control works correctly in C#, and I can find the relevant model that goes with the id. It all appears correct on the C# controller side. However, when I try to get it to redirect back to the same edit page but with a different id (that from the dropdown), the page reverts back to the ajax call.
Is there anyway to "short-circuit" the ajax call so that it "knows" that it doesn't return but lets the C# redirect to the edit page (just like what happens when an element is chosen from the index page).
Thanks in advance,
Joseph Doggie
If you are making ajax requet, then you have to implement a way to redirect.
Depends on your ajax protocol... Are you returning json? html ...
If returning json, you could add a flag in your response telling wether this is a redirect answer and do redirect in js :
window.location = url
OK, there is at least one way to do this.
Assume editing X with Controller named YController:
JavaScript:
var MyControllerUrlSettings = {
MyControllerPrepareModifyXInfoUrl: '#Url.Action("PrepareModifyAssetInfo", "Y", new { x_txt = "param" })'
}
one then has a JavaScript to handle the dropdown change:
$('#ModelXList').change(function () {
//// alert('Change detected');
if ($("#ModelXList").val() != "") {
//// alert('Reached here');
var XNbrString = $("#ModelXList").val();
var trimmedXNbrString = $.trim(XNbrString);
//// debugger;
if (trimmedXNbrString != "") {
var url = MyControllerUrlSettings.MyControllerPrepareXInfoUrl;
window.location.href = url.replace('__param__', trimmedXNbrString);
}
}
else {
}
});
Finally, in the controller, there is a method:
public ActionResult PrepareModifyXInfo(string XNbr_txt)
{
// we cannot save anything here to cdll_cdcloanerlist;
// static variables must be used instead.
/// .... do what you have to do....
return RedirectToAction("ModifyEdit", new { XNbr_txt = XNbr_txt });
}
Note: For proprietary reasons, I changed some of the syntax so that everything would be general, therefore, you may have to work with the above code a little, but it works
Alternate answers are really welcome, also!
am having Sample.aspx and sample.js both are in different directory.
how can i get the Sample.aspx page session values in sample.js file ?
i cant get the value for the following types
function session() {
alert('<%=Session.getAttribute("hdn_CheckedData")%>');
alert(document.getElementbyId("hdn_CheckedData").value);
alert('<%=Session["CheckedData"]%>');
alert('<%=Session("CheckedData")%>');
alert('<%=Session["CheckedData"].ToString()%>');
alert('<%=Session("CheckedData").ToString()%>');
};
CheckedData - is the session
hdn_CheckedData - is the hiddenfield
i tried both of it.
is it possible then help me pls.....
Hiddenfiled, session, viewstate or anything............
One simple solution is to declare the session variables just before the load of your javascript file and inside the aspx page. Eg on sample.aspx you have
<script>
var sessionCheckData = "<%=session["CheckedData"].ToString()%>";
</script>
<script type="text/javascript" src="sample.js"></script>
and on sample.js you have
function session() {
alert(sessionCheckData);
};
Similar answer: How to get asp.net client id at external javascript file
You can save the session data to a hidden field on your page. After that you have direct access to that field in you js file.
Or you can declare a session variable as Aristos has proposed. That would more straightforward actually.
I would write a generic handler and use JSONP to pass any data to external Javascript.
Please take a look at here, here and here.
Since it is not cross domain, JSON should also work.
You have to assign session values to hiddenfield
after that you can use that values
I am wondering How i can keep the text of my textbox even if i have to make a new page load, clicking on an hyperlink.
It's always an empty string.
Can someone help me ?
lkForgotten.NavigateUrl = string.Format("Logon.aspx?forgotten={0}", "");
lkSend.NavigateUrl = string.Format("Logon.aspx?forgotten={0}&userEmail={1}", "submited", txtForgotten.Text);
try
{
if (Request.QueryString["forgotten"].ToString() == "")
{
txtForgotten.Visible = true;
lkSend.Visible = true;
}
if (Request.QueryString["forgotten"].ToString() == "submited")
{
userEmail = txtForgotten.Text;
SendForgottenPassword(userEmail);
}
}
catch { }
If you need to persist some data specific to the person, you can use a session. It is precisely the thing you need.
You can set it whenever you want and get the values you need.
http://msdn.microsoft.com/en-us/library/ms178581.aspx
Edit:
To satisfy some objections raised in comments, if the session itself isn't enough, you can still use a different approach. Monitor the textboxes with javascript and if their value is changed, add a cookie (or add a value to existing cookie, depends on the needs). Still much better approach than using querystring for this type of functionality... At least in my opinion.
Edit
Do the redirection with the
Javascript code
function redirect()
{
var val = document.getElementById('<%= txtForgotten.ClientID %>').value;
location.href='Logon.aspx?forgotten=submitted&userEmail=' + val ;
}
<input type="button" VALUE="Visit Microsoft" OnClick="redirect();">
problem witht he above code is when you are creating the url of forget password on page load at that time textbox value is empty and when do redirection by clicking forget password link its getting empty value only rather what you typed in your code...so to make it work do the redirection using javascript as above or make use of click event that do the redirection for you....
Org
following line change like this
if (Request.QueryString["forgotten"].ToString() == "submited") {
userEmail = txtForgotten.Text = Request.QueryString["userEmail"].ToString() ;
SendForgottenPassword(userEmail);
}
so when you are clicking button it get the value of userEmail from the querystring and restore value in you textbox ...this will surely do your task
or
you can make use of other client side mecanisam like cookies to store the value and than retrive it back on page...
serverside option is session variable also helpfull if you want to store the value and retrieve it back.....
My project implements search (from default HTML page) and will redirect to the search page (ASPX page) and I'm using query string to pass the search value. I'm getting potentially dangerous Request.QueryString value server error when language is set to non-english (e.g. thai, cyrillic).
Is there any way to handle this from client side? Currently I can't find a way to handle this from the page itself (Page_Load, Page_PreInit isn't triggering).
Here's the code I used for redirecting:
function Search() {
var searchString = document.getElementById('txtSearch').value;
location.href = "/Search.aspx?search=" + searchString;
}
Adding validateRequest="false" to you .Net Page or Web.config file
OR
you can encode your url vars, adding encodeURIComponent:
function Search() {
var searchString = document.getElementById('txtSearch').value;
location.href = "/Search.aspx?search=" + encodeURIComponent(searchString);
}
If your data is going to look roughly like code you may well have to disable this validation; but then you need to be really sure about your code handling, in particular avoiding XSS and SQL injection attacks. You should be able to set in the aspx validateRequest=false to disable on a per-page basis:
<%# Page validateRequest="false" ...
or globally in the web.config if you need this everywhere.