In this article I will explain with an example, how to set TempData using JavaScript or jQuery in ASP.Net MVC Razor.
TempData is created on Server Side of the Web application and hence it is not possible to directly set it on Client Side using JavaScript or jQuery.
Thus, only possible way is to set it by making an AJAX call to the Controller’s Action method using jQuery AJAX function in ASP.Net MVC Razor.
 
 
Controller
The Controller consists of two Action methods.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
 
Action method for handling jQuery AJAX operation
This Action method handles the call made from the jQuery AJAX function from the View.
Note: The following Action method does not return any data and hence the return type is set to EmptyResult.
 
The value of the value parameter is assigned to the TempData object and an EmptyResult is returned.
public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        return View();
    }
 
    [HttpPost]
    public ActionResult SetTempData(string value)
    {
        TempData["Message"] = value;
        return new EmptyResult();
    }
}
 
 
View
The View consists of an HTML Button assigned with an OnClick event handler.
Just below the Button, the value of the TempData object is displayed using Razor syntax.
When the Set Button is clicked, the SetTempData JavaScript function is called.
Inside the SetTempData function, a jQuery AJAX call is made to the Controller’s Action method where the TempData object is set with the value.
Finally, inside the Success event handler, the Page is reloaded (refreshed) with the help of JavaScript window.location property.
After the pages is reloaded (refreshed), the value of the TempData object set on Client Side is displayed.
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
</head>
<body>
    <input type='button' value='Set TempData' onclick="SetTempData()"/>
    <hr/>
    @TempData["Message"]
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type='text/javascript'>
        function SetTempData() {
            $.ajax({
                type: "POST",
                url: '/Home/SetTempData',
                data: '{ value: "Hello Mudassar!"}',
                contentType: "application/json; charset=utf-8",
                dataType: "text",
                success: function (r) {
                    window.location = window.location.href;
                }
            });
        }
    </script>
</body>
</html>
 
 
Screenshot
Set TempData using JavaScript or jQuery in ASP.Net MVC
 
 
Downloads