Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How set Session variables in ASP.NET MVC 3 with jQuery?

So this is the question: how set Session variables in ASP.NET MVC 3 with jQuery?
I'm trying to use $.ajax or $.post but the problem is that I don't really know what to do.

like image 914
Arсiom Prudnikaŭ Avatar asked Jan 03 '12 12:01

Arсiom Prudnikaŭ


People also ask

How can access session variable in jQuery in MVC?

You cannot "Access Session from jQuery". You use MVC and asp.net to create an HTML page (with JavaScript). Session is a server-side object, and JavaScript runs on the client side.

How can store value in session using jQuery in ASP NET?

ToInt32(val); Session["AshDiffuserID"] = ash_diffuser_id; } else if(key == "PesterchumHandle") { string handle = val; Session["PesterchumHandle"] = handle; } else // etc... After that, you'll need to set up a post HTTP request through jquery that puts whatever values you need in those "key" and "val" fields.

Can we set session value in jQuery?

jQuery is a JavaScript library and JavaScript is a Client Side language and hence directly it is not possible to set Session variable in jQuery.


1 Answers

Description

Just post to a controller and set the Session variable there.

Sample

jQuery

$(function () {
    $.post('/SetSession/SetVariable', 
           { key : "TestKey", value : 'Test' }, function (data) 
    {
        alert("Success " + data.success);
    });
});

Mvc Controller

public class SetSessionController : Controller
{
    public ActionResult SetVariable(string key, string value)
    {
        Session[key] = value;

        return this.Json(new { success = true });
    }
}

More Information

  • Save and retrieve Session data via Ajax using JQuery in an MVC 3 application
like image 197
dknaack Avatar answered Sep 24 '22 08:09

dknaack