Set asp.net mvc session values using jQuery

QuestionsCategory: Asp.netSet asp.net mvc session values using jQuery
Alen asked 4 years ago

How to Set asp.net MVC session values using jQuery?

I want to set the Dropdown selected value in Session. I have done in Code behind. But for some condition, i have to Do in Client Side Itself.

 

Disclosure of Material Connection: Some of the links in the post above are “affiliate links.” This means if you click on the link and purchase the item, we will receive an affiliate commission. Regardless, we only recommend products or services we use personally and believe will add value to our readers.

1 Answers
Shehryar Khan Staff answered 4 years ago

you can directly Get the value of Session in JavaScript but setting Session value from JavaScript is little tricky.
You can do something like this..
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 });
    }
}

 

 

Disclosure of Material Connection: Some of the links in the post above are “affiliate links.” This means if you click on the link and purchase the item, we will receive an affiliate commission. Regardless, we only recommend products or services we use personally and believe will add value to our readers.