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.
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!');";
}
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With