Yogurtu
Yogurtu

Reputation: 3031

MVC, How to read rendered HTML in a controller?

Maybe it´s a strange question, but imagine this:

//We all know that View is a method...
public ActionResult Something()
{
    return View("index");
}

But what if I step before this method to perform some stats

public ActionResult Something()
{
    return PerformStats(View("index"));
}

I will have a private method like this:

private ActionResult PerformStats(ViewResult viewResult)
{

    //THIS IS WHAT I WANT TO ACCHIEVE:
    //*********************************

    var contentSent = viewResult.InnerHtml.Lengh; <<-- I wish!

    return viewResult;
}

And latter, what i want to do, is to save that ammount of content sent to the client. It doesn´t matter if it is the exactly quantity of html, even if I get the .count() of a json it will do the trick.

Is any way to know the rendered content on the controller?

Thanks!

Upvotes: 1

Views: 422

Answers (1)

user338195
user338195

Reputation:

OnActionExecuting: Called before action method executes. You can put stats related logic in there.

http://msdn.microsoft.com/en-us/library/system.web.mvc.iactionfilter.onactionexecuting(v=vs.98).aspx

OnActionExecuted: Called after action method executed.

http://msdn.microsoft.com/en-us/library/system.web.mvc.iactionfilter.onactionexecuted(v=vs.98).aspx

Within these methods you can access ActionExecuting and ActionExecutedContext

If you want to get a size of rendered HTML (partial or complete view), then you probably need to:

  • Find the view that you want to render
  • Store it in the string builder
  • Get its length

There is a question that explains how to render view as a string within the action method: In MVC3 Razor, how do I get the html of a rendered view inside an action?

Upvotes: 1

Related Questions