Inject javascript on every controller action - asp.net mvc

11,886

Solution 1

Look into overriding the base controller's OnActionExecuted event, which should provide you access to the view model after it has been processed by the action. I'm curious though, how exactly are you going to inject a snippet of javascript into an AJAX response, which is typically a simple JSON object?

If all you're really asking is how to inject javascript from the controller, you could put the following in your view:

<script type="text/javascript" defer="defer">
    @Html.Raw(ViewBag.StartupScript)
</script>

You could add the above to a specific view, or a layout page. Then, you could do something like this:

public class MyController : Controller
{
    public override void OnActionExecuted(...)
    {
        if (...)
        {
            ViewBag.StartupScript = "alert('hello world!');";
        }
    }
}

Solution 2

To inject on postback as well as ajax calls here is how you can do it:

protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
            StringBuilder sb = new StringBuilder();
            sb.Append("<script type=\"text/javascript\">\n\t");
            sb.Append("alert('Hello Injection');");
            sb.Append("</script>\n");
            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                filterContext.HttpContext.Response.Write(sb.ToString());
            }
            else
            {
                ViewBag.StartupScript = sb.ToString();
            }
}

Probably not the cleanest solution, but works.

Share:
11,886
user784796
Author by

user784796

Updated on June 07, 2022

Comments

  • user784796
    user784796 almost 2 years

    Whenever we make a call to any action controller whether through a full post back or an ajax call I want to check the view model and depending on some logic inject some javascript to be executed in the browser. The application is mostly already coded and what I am trying to do is to have some generic code which can do the trick. I am wondering what would be the best way to do it. I am thinking about using action filters and then checking the model and then inject the js if required. But not sure how would that work on events like action executed etc. Any code sample will be helpful.

    The other option is to do it on the client side. But again not sure how to properly do it in a generic way.

  • user784796
    user784796 about 12 years
    Yes the part I know. My question is exactly what you are asking as well. How can one inject javascript to be executed at client side in this event? In asp.net web forms there is register script, but not if in mvc there is way to do it.
  • Chris
    Chris about 12 years
    I added an example to my post.
  • user784796
    user784796 about 12 years
    That works. Thanks Chris. Just few corrections. in your controller code there is a semicolon missing. ViewBag.StartupScript = "alert('hello world!');"; And the in the view it should be @Html.Raw(@ViewBag.StartupScript) otherwise your script will not run.
  • Chris
    Chris about 12 years
    Haha you're right. Shame on me for not testing the code first. I'll update the post for reference.
  • Chris
    Chris about 12 years
    Also, you don't need the second @ symbol inside the parentheses.
  • user784796
    user784796 about 12 years
    Chris not sure if it will work in ajax calls? As the layout wont be rendered and only partial view will be.
  • Chris
    Chris about 12 years
    If you're using Ajax to render a partial view, then yes, the partial view would also need the script tags. However, keep in mind anyway that javascript contained in dynamically loaded HTML is not automatically executed by the browser. See stackoverflow.com/questions/5668219/… and stackoverflow.com/questions/889967/… for more info. For AJAX calls, I'd strongly recommend you return JSON instead of HTML and manipulate the dom accordingly with the JSON received.