Jamie Dixon
Jamie Dixon

Reputation: 53991

Partial View to String in MVC 3

Searching around I haven't found any recent answers to this question.

The other answers I have found focus on versions 1 & 2 of the MVC framework.

Now with MVC 3, is there a simple way to execute and return a partial view as a string or should we still be implimenting our own solution? as can be found in other answers such as:

ASP.NET MVC Razor: How to render a Razor Partial View's HTML inside the controller action

(note that the article presented in the accepted answer refers to MVC 2).

Upvotes: 1

Views: 6862

Answers (1)

Jamie Dixon
Jamie Dixon

Reputation: 53991

To render a partial to a string in MVC3 we can make use of the HtmlHelper.Partial method.

Renders the specified partial view as an HTML-encoded string.

Source: MSDN

An example of this can be seen in the HtmlHelper extension that I wrote for RenderPartials enabling the rendering of a single partial n times based on a collection. (mitigating the need for loops in the view)

public static void RenderPartials<T>(this HtmlHelper helper, 
                                     string partialViewName, 
                                     IEnumerable<T> models, 
                                     string htmlFormat)
        {
            if (models == null)
                return;

            foreach (var result in models
                                   .Select(
                                      item => helper.Partial(partialViewName, item)))
            {
                helper.ViewContext.Writer.Write(htmlFormat, result);
            }
        }

Upvotes: 2

Related Questions