Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject javascript on every controller action - asp.net mvc

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.

like image 724
user784796 Avatar asked Jan 17 '23 23:01

user784796


2 Answers

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!');";
        }
    }
}
like image 140
Chris Avatar answered Jan 21 '23 08:01

Chris


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.

like image 43
user784796 Avatar answered Jan 21 '23 10:01

user784796