user1930845
user1930845

Reputation:

MVC 4 read data from controller in a view using ajax

I managed to post with ajax to a controller everything is good and I can see the data inside a controller. This is what I did:

$.ajax({
    type: "POST",
     url: "./Enroll/saveTempSelectedPlan",
 content: "application/json; charset=utf-8",
    data: ({tempSelectedPlan: plan, tempSelectedTier: tier}),
 success: function() {alert("SUCCESS");}, 
   error: function() {alert("FAIL");}
});

and inside a controller this is how I read data:

public JsonResult saveTempSelectedPlan(string tempSelectedPlan, string tempSelectedTier)
{
    Session["TemporarySelectedPlanNumber"] = tempSelectedPlan;
    Session["TemporarySelectedTierNumber"] = tempSelectedTier;
    return Json("SUCCESS");
}

Now I am trying to post that data back out to a view, like this:

public JsonResult loadTempSelectedPlan()
{
    if (Session["TemporarySelectedPlanNumber"] != null && Session["TemporarySelectedTierNumber"] != null)
    {
        return Json(new { 
        tempSelectedPlan = this.HttpContext.Session["TemporarySelectedPlanNumber"].ToString(),
        tempSelectedTier = this.HttpContext.Session["TemporarySelectedTierNumber"].ToString()
    });
}

return Json("SUCCESS");

}

My question is how can I read that data back in the view do I create another post (would probably be GET). How do I read that data back in the view. Also if any improvements would be highly appreciated!

Thank you.

Upvotes: 1

Views: 1192

Answers (1)

Travis J
Travis J

Reputation: 82287

First is the return value. Whatever you pass as an argument into Json(arg) will be serialized. The serialized arg is going to be in the JSON format.

Your success function will be injected with this as a parameter

success: function(data) {console.log(data);}, //now you can examine it

Also keep in mind that you can always inspect the response headers in your dev console of your browser. The returned json will be in there as well.

Upvotes: 1

Related Questions