Mike Mike -4 years ago 278
Ajax Question

Unable to extract the string i want from the ajax post

In my asp mvc project i've got an ajax call that posts the value of a dropdown list and i want the session to be set with this value.

$('#dropDownMenu').on('click', 'li', function () {
var txt = $('#schoolButtons').text();
data = {session: txt};
var requestValue = JSON.stringify(data);

url: '@Url.Action("SetSession")',
type: 'POST',
data: "requestValue="+requestValue ,
}).success(function (data, textStatus, jqXHR) {


public ActionResult SetSession(string requestValue)
var sessionVal = Convert.ToString(requestValue);
if (sessionVal==null)
Debug.WriteLine("session is null");

Session["key"] = sessionVal;
return Json(requestValue);

When I output the value of the session i'm getting the string {"session":"State School"} when all i want is "State School". I know in the function data is set to {session: txt} but how do i just extract that txt?



Answer Source

To read the JSON value you need to read it this way

var requestValue = data.session

Since you pass it as a string into the function and want to read it in the function, this is what I sugggest you do. You need to convert the string to JSON and extract the value.

public ActionResult SetSession(string requestValue)
    var JSONData = JSON.parse(requestValue);
    var sessionVal = JSONData.session;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download