简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM