How can i retrive session from asp.net using Jquery - asp.net

How can I retrieve session variable stored in a.aspx using Jquery? I have username stored in the session, I need to retrieve the session to display the username in the menu bar.
A person login through A.aspx and his details has to be displayed(from database) in B.aspx

One way to handle this would be to create a Web Method or similar within your current page so that you could access the updated value of the Session via an AJAX call :
[WebMethod]
public static string GetSessionValue(string key)
{
return Session[key];
}
Then you could make a POST call via AJAX to request the specific key that you needed (or you could ignore any parameters and simply hard-code the key that you wanted to pull within the method itself) :
public static string GetSessionDisplayName()
{
// Use the name of your Session key here to retrieve your info
return Session["DisplayName"];
}
And then you could use the following jQuery code to pull it with a parameter :
$.ajax({
type: "POST",
url: "YourPage.aspx/GetSessionValue",
data: '{ key: "your-session-key" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
// data will hold your Session value, use it here
alert(data);
}
});
Or without one :
$.post('YourPage.aspx/GetSessionDisplayName',function(data){
// data will hold your Session value, use it here
alert(data);
});

Related

How to retrieve JSON objects from ASP.NET Web Form

I am passing JSON data to asp.net web form in script. How can I retrieve the id and use in web form
$.ajax({
type: "GET",
url: 'Edit.aspx',
cache: false,
data: ({
id: id,
page: lastDirecotry
}),
success: function (data) {
$("#dialog").html(data);
$("#dialog").dialog("open");
}
});
This is the key piece of information:
type: "GET"
Since this is a GET request, the data is going to be query string key/value pairs. So if this is the data being sent:
{ id: id, page: lastDirecotry }
Then you can get those values server-side from here:
var id = Request.QueryString["id"];
var page = Request.QueryString["page"];
in success method you can get data.id to fetch id ,and to fetch page parameter data.page will give you lastDirectory

How to get post data as json in asp.net?

I am making an ajax request to my API but my API expects raw json data to parse its own objects in C# how do I get the raw Json data in C#? from the "HttpContext.Current.Request"
Here is my request:
$.ajax({
url: '/REST/GetResponse.cshtml',
type: "POST",
contentType: "Application/JSON",
data: {
code: "login",
data: {
username: $("#login_username").val(),
password: $("#login_password").val(),
rememberMe: $("#rememberMe").val()
}
},
success: function (result) {
},
error: function (result) {
console.log(result);
}
});
You should be able to get body of the request using property 'HttpRequest.InputStream`. The type of the property is a stream, but you can see an example on MSDN on how to convert it to string.
Depending of what is your underlying framework there can be easier ways to get the body. E.g. MVC of Web API use binding to map incoming requests to objects, so it might be an option to consider.

Call controller which returns view in javascript

I am working in ASP.Net MVC. I have following Javascript code in which i am calling a controller-method which returns a view. I want to send parameters to a controller method which re
function fun(p1,p2)
{
// code here to call controller method which returns view
}
public ActionResult ProblemDetails(p1,p2)
{
// here goes some code.
return View();
}
Please tell me the code which can be used to call controller and send parameters too.
Action Method
public ActionResult SendStream(string a, string b)
{
}
JQuery/JSON
Please note that Get Verb will not support complex Data parameters due to it's Query string length constraint. So use POST Verb instead of GET Verb while sending large data
$.ajax({
url: url,
data: JSON.stringify({ a: "a", b: "b" }), //Two String Parameters
type: 'GET', //For Submit, use POST
contentType: 'application/json, charset=utf-8',
dataType: 'json'
}).done(function (data) {
//Success Callback
}).fail(function (data) {
//Failed Callback
}).always(function(data) {
//Request completed Callback
});
Are you perhaps looking to return a Partial View? You can use jQuery ajax to post to a controller method that returns a Partial View (html). You can then render that HTML on the page.
http://mazharkaunain.blogspot.com/2011/04/aspnet-mvc-render-partial-view-using.html
jQuery.get is the shorthand way to achieve this.
function fun(p1,p2)
{
var url = '/controller/ProblemDetails?p1=' + p1 + '&p2=' + p2;
$.get(url, function (data) {
// data will be your response as html
});
}
I might also suggest to have the action return PartialView() instead of View() since you will not return the layout along with the response. It all depends on your intentions for the returned html.
There are several ways to do it.
For example Ajax:
Quick note first: Make sure that in your MVC routing configuration you have a route configured to reflect the following url below:
function fun(p1,p2)
{
var url = '/ControllerName/ProblemDetails?p1=p1&p2=p2' //url to your action method
$.ajax({
url:url,
type:'post' or 'get', //(depending on how you're doing this. If post you can pass data internally instead of query string ),
dataType:'html', //(for example)
success:function(data){
//data here will contain your View info so you can append it do div for example. You can use JQuery .html() function for that
error: function (xhr) {
//catch error
}
}
})
}
Another way, in case if you want to load your View data to DIV is to use JQUery functions such as .load();
function fun(p1,p2)
{
var url = '/ControllerName/ProblemDetails?p1=p1&p2=p2';
$('#YourDivTagForExample').load(url);
}
$.ajax call can also be abbriviated to $.get, $.post or $.getJSON depending on what kind of a call you want to make to your action method. There is a lot more to it too.
Finally make sure to take a look at this answer. Your question was actually already answered in full:
Correct way to handle Ajax calls in ASP.Net MVC 3
Use JSONResult instead of ActionResult and Manipulate return data in javascript.

Generating new SessionId in ASP.NET

On login I want to generate a new SessionId. I have found one solution that works, but it requires some pretty hackish things and requires the app have Full Trust securityPolicy setting.
Is there any other way to achieve this?
Looks like this works:
Session.Abandon();
Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", ""));
By clearing out that cookie, a new session with a new session ID will be created at the server.
(Reference: Microsoft Support)
EDIT: Here's an example using AJAX (with jQuery) to call the server code without a page refresh - it calls twice, once to remove the first session, and once to generate a new one. There may be a better way, but this does work.
function newSession() {
jQuery.ajax({
type: "POST",
url: "WebForm1.aspx/ClearSession",
data: "{}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function () {
jQuery.ajax({
type: "POST",
url: "WebForm1.aspx/NewSession",
data: "{}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function () { console.log("Success!"); },
error: function (x, y, z) {
console.log("Failure!");
}
});
},
error: function (x, y, z) {
console.log("Failure!");
}
});
}
And on the code-behind (for WebForms - you could also do this with an MVC controller):
[WebMethod]
public static void ClearSession()
{
HttpContext.Current.Session.Abandon();
HttpContext.Current.Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", ""));
}
[WebMethod]
public static void NewSession()
{
HttpContext.Current.Session["x"] = 123;
}
I'm currently considering a configuration-based solution, rather than a code-based one. I would configure either the web server or load balancer to strip away request and response headers containing cookies for just the login page. Remove the "cookie" headers for request headers and "set-cookie" for response headers.
Every request (GET or POST) to the login page will contain no cookie information, thus forcing ASP.NET to create a new session and (more importantly) a new session id.
It's less efficient than forcing a new session creation on login, but the technique could be useful in cases where you cannot modify the code.

How to pass parameter back from asp.net web service if an insert to a database was successful? ASP.NET/jQuery/AJAX/JSON

I have a web form and I use jQuery/AJAX/JSON to send objects to a web service using:
$.ajax({
type: "POST",
url: "SynchroniseCustomers.asmx/synchroniseCustomers",
data: JSON.stringify(customerObj),
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (xhr, status) {},
success: function (msg) {}
});
From the web service I want to check if the insert into the database was successfull, return a variable with an ID and pass this ID to a function. In the object I have the ID so I could have:
success: function (msg) {deleteCustomer(ID);}
But this only checks if the data was passed to my method in the web service?
I have followed this example
http://encosia.com/2009/04/07/using-complex-types-to-make-calling-services-less-complex/
and in the class Person I get a message back from the database server telling me if the insert was successfull or not so like:
if (successfull)
{
return ID;
}
Is there a way to get this ID back to the web form and use this in a variable?
Thanks in advance.
You want to return a result object with an isSuccess and id property. You can then do the following:
success: function (result) {
if (!result.isSuccess) {
// display friendly error message indicating that the db insert failed
} else {
var id = result.id;
// do client side processing with primary key returned from db insert
}
}
How you return the result object depends on your web services framework (e.g., WCF, MVC, WebMethod, etc.). The framework will serialize your .NET object to a JSON encoded result (e.g., { isSuccess: true, id: '1234'}).
As an example, in ASP.NET MVC you simply return a JsonResult using Json.(MySerializableResult). If you post what you are using for web services, I'm sure you'll get a specific answer to that framework.

Resources