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