Click here to Skip to main content
15,887,683 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
Why we cannot access/get TempData in ajax request.

For example:

Controller:

C#
TempData["MyMessage"] = MyMessage;
 return Json(true, JsonRequestBehavior.AllowGet);


View:

$.ajax(
{
url: '@Url.Action("someAction")',
dataType: 'json',
data: $("form").serialize(),
type: 'POST',
success: function (result) {
value=TempData["MyMessage"];//why this is not possible

},
error: function (xhr) {
alert(xhr.statusText);
}
});


I know i can get my message using json , but i want to know the reason that why the tempdata is not accessible in ajax request.
Posted
Updated 19-Jul-19 1:55am
v2
Comments
Sergey Alexandrovich Kryukov 25-Aug-15 9:33am    
I just does not seem to make any sense. You never use result.
—SA

1 solution

It's not possible because TempData only exists in server-side coding and you're trying to use it on the client in javascript. If the js is directly on the view you could do something like

value='@TempData["MyMessage"]';


That will only work if the TempData was set before the page was sent to the client though, it won't work if TempData is set in the ajax method. This is because your view is generating static html that is sent to the client, so if you look at the source you'll see your js look like

C#
success: function (result) {
 value='Whatever is in TempData when the page loads';


If nothing is in TempData then it will look like

C#
success: function (result) {
 value='';


So no matter what happens inside your ajax method, the success event in your js is always going to set value to be the same thing. Remember js runs off whatever is sent to the client, not from your cshtml view, and your .net code isn't running "inside" the browser, the browser's html is not a live object your server code can freely interact with.

However what you should do is make your request return an object with two values, the success and the message

return Json(new{success=true, value=MyMessage}, JsonRequestBehavior.AllowGet);


in your js;

success: function (result) {
    success = result.success;
    value=result.value;
 
Share this answer
 
v3
Comments
Sergey Alexandrovich Kryukov 25-Aug-15 9:31am    
5ed.
—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900