Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append custom HTML to the end of view with attributes in ASP.NET MVC?

Assume we have some action in controller:

public ActionResult SomeAction()
{
    return View();
}

I want to have a possibility to append some HTML code to the end of view's HTML result with help of attributes, e.g.:

[SomeHTML]
public ActionResult SomeAction()
{
    return View();
}

where

public class SomeHTMLAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        var response = filterContext.HttpContext.Response;

        if (response.ContentType == "text/html")
        {
            response.Write("someHTML");
        }
    }
}

Filters (ActionFilterAttribute) allow to append some HTML code to the top or bottom of web-page but not to the end of view's HTML.

How to archive this?

like image 445
sashaeve Avatar asked Aug 31 '11 13:08

sashaeve


1 Answers

You could use a Response filter:

public class SomeHTMLAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        filterContext.HttpContext.Response.Filter = new SomeHTMLFilter(filterContext.HttpContext.Response.Filter);
        base.OnActionExecuting(filterContext);
    }
}

public class SomeHTMLFilter : MemoryStream
{
    private readonly Stream _outputStream;
    public SomeHTMLFilter(Stream outputStream)
    {
        _outputStream = outputStream;
    }

    public override void Write(byte[] buffer, int offset, int count)
    {
        _outputStream.Write(buffer, 0, buffer.Length);
    }

    public override void Close()
    {
        var buffer = Encoding.UTF8.GetBytes("Hello World");
        _outputStream.Write(buffer, 0, buffer.Length);
        base.Close();
    }
}
like image 92
Darin Dimitrov Avatar answered Oct 06 '22 00:10

Darin Dimitrov