Skip to content Skip to sidebar Skip to footer

Parse Attributes From MvcHtmlString

I need to be able to parse the attributes from an MvcHtmlString (the results of an HtmlHelper extension), so that I can update and add to them. For example, take this HTML element:

Solution 1:

One idea to accomplish what you want is to use a global action filter. This will take the results of the action and allow you to modify them before they are sent back to the browser. I used this technique to add CSS classes to the body tag of the page, but I believe it will work for your application too.

Here is the code (boiled down to the basics) that I used:

public class GlobalCssClassFilter : ActionFilterAttribute {
    public override void OnActionExecuting(ActionExecutingContext filterContext) {
        //build the data you need for the filter here and put it into the filterContext
        //ex: filterContext.HttpContext.Items.Add("key", "value");

        //activate the filter, passing the HtppContext we will need in the filter.
        filterContext.HttpContext.Response.Filter = new GlobalCssStream(filterContext.HttpContext);
    }
}

public class GlobalCssStream : MemoryStream {
    //to store the context for retrieving the area, controller, and action
    private readonly HttpContextBase _context;

    //to store the response for the Write override
    private readonly Stream _response;

    public GlobalCssStream(HttpContextBase context) {
        _context = context;
        _response = context.Response.Filter;
    }

    public override void Write(byte[] buffer, int offset, int count) {
        //get the text of the page being output
        var html = Encoding.UTF8.GetString(buffer);

        //get the data from the context
        //ex var area = _context.Items["key"] == null ? "" : _context.Items["key"].ToString();

        //find your tags and add the new ones here
        //modify the 'html' variable to accomplish this

        //put the modified page back to the response.
        buffer = Encoding.UTF8.GetBytes(html);
        _response.Write(buffer, offset, buffer.Length);
    }
}

One thing to watch out for is that the HTML is buffered into, I believe, 8K chunks, so you might have to determine how to deal with that if you have pages over that size. For my application, I didn't have to deal with that.

Also, since everything is sent through this filter, you need to be sure that the changes you are making won't effect things on things like JSON results.


Post a Comment for "Parse Attributes From MvcHtmlString"