In this article, we will learn how to execute a JavaScript function from the controller. The problem is the controller exists on the server-side whereas the view is rendered on the client-side. Once the view is rendered in the browser, it doesn’t have any communication with the controller.

How to Call JavaScript function from the Controller using C#

If the JS function you need to call doesn’t return any value, you can just render the function using JavaScript ActionResult:

    public ActionResult MyAction()
    {
        return JavaScript("window.alert('Hello World');");
    }

In case you have to return a value from JS function, the only solution here is to use a ViewBag.

ViewBag is a dynamic object which enables you to share values between the controller and view in Asp.Net MVC applications. You can use ViewBag to transfer small amounts of data such as shopping carts, dropdown lists, widgets, etc. It allows you to set or get values dynamically which means you can add additional data without a strongly-typed class and pass it from the controller to view.

You can define properties on a dynamic object to access the values in a view.

The syntax for using ViewBag in C# is:

public object ViewBag { get; }

Let’s create a simple JS function in the View that displays the name of the user.

View

    @using (Html.BeginForm("Index", "Home", FormMethod.Post))
    {
    <input type="text" id="txtName" name="name" />
    <input type="submit" id="btnSubmit" value="Submit" />
    }

The form has a text box for the user’s name and a submit button.

JavaScript

<script type="text/javascript">
    function ShowGreetings(name) {
        alert("Name: " + name);
    };

</script>
@if (ViewBag.JavaScriptFunction != null) {
    <script type="text/javascript">
        @Html.Raw(ViewBag.JavaScriptFunction)
</script>
}

After the user enters the name and clicks on the submit button, the name value is fetched. The ViewBag object now contains the JS function’s script. The script is rendered in the View and will execute the respective function once the view is rendered and loaded in the web browser at the client’s end.

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Index(string name)
        {
            if (!string.IsNullOrEmpty(name))
            {
                ViewBag.JavaScriptFunction = string.Format("ShowGreetings('{0}');", name);
            }
            return View();
        }
    }

Related Articles

Last modified: November 8, 2019

Comments

Write a Reply or Comment

Your email address will not be published.