In this article I will explain with an example, how to set ViewData using JavaScript or jQuery in ASP.Net MVC Razor.
ViewData 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 ViewData object and an EmptyResult is returned.
public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        return View();
    }
 
    [HttpPost]
    public ActionResult SetViewData(string value)
    {
        ViewData["Message"] = value;
        return new EmptyResult();
    }
}
 
 
View
The View consists of an HTML Button assigned with an OnClick event handler.
When the Set Button is clicked, the SetViewData JavaScript function is called.
Inside the SetViewData function, a jQuery AJAX call is made to the Controller’s Action method where the ViewData object is set with the value.
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
</head>
<body>
    <input type='button' value='Set ViewData' onclick="SetViewData()"/>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type='text/javascript'>
        function SetViewData() {
            $.ajax({
                type: "POST",
                url: '/Home/SetViewData',
                data: '{ value: "Hello Mudassar!"}',
                contentType: "application/json; charset=utf-8",
                dataType: "text",
                success: function (r) {
                   
                }
            });
        }
    </script>
</body>
</html>
 
 
Screenshot
Set ViewData using JavaScript or jQuery in ASP.Net MVC
 
 
Downloads