Introduce javascript for each controller action - asp.net mvc

Whenever we turn to any action controller, regardless of whether through a full post or ajax call, I want to check the presentation model and, depending on some logic, insert some javascript that will be executed in the browser. The application is basically already encoded and what I'm trying to do is to have a common code that can do the trick. I am wondering what would be the best way to do this. I think about using action filters, and then checking the model, and then inserting js if necessary. But I'm not sure how this will work on events such as an action being performed, etc. Any sample code will be helpful.

Another option is to do this on the client side. But again, I’m not sure how to do it in a general way.

+3
source share
3 answers

Look at the redefinition of the OnActionExecuted base controller, which should give you access to the view model after it has been processed by the action. I'm curious how exactly are you going to inject a javascript snippet into the AJAX response, which is usually a simple JSON object?

If you are really asking how to add javascript from the controller, you can specify the following:

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

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

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

For inputting feedback, as well as for ajax calls, you can do this:

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();
            }
}

, , .

+1

filterContext.HttpContext.Response.Write (sb.ToString ()); this will override the partial view coming from an Ajax call, any move around?

0
source

All Articles