0

I need to render a partial view to a string within a controller action. I have the following sample code, but the ControllerContext.ParentActionViewContext does not seem to exist in mvc 1.0

            // Get the IView of the PartialView object.
            var view = PartialView("MyPartialView").View;

            // Initialize a StringWriter for rendering the output.
            var writer = new StringWriter();

            // Do the actual rendering.
            view.Render(ControllerContext.ParentActionViewContext, writer);

Any tips greatly appreciated.

1

2 Answers 2

1

Here's one way to achieve this. There's also a BlockRenderer in MvcContrib.

Sign up to request clarification or add additional context in comments.

Comments

1

try this MVC v1.0 (an extension method that i use)

public static class Extensionmethods
{
    public static string RenderPartialToString(this Controller controller, string partialName)
    {
        return RenderPartialToString(controller, partialName, new object());
    }
    public static string RenderPartialToString(this Controller controller, string partialName, object model)
    {
        var vd = new ViewDataDictionary(controller.ViewData);
        var vp = new ViewPage
        {
            ViewData = vd,
            ViewContext = new ViewContext(),
            Url = new UrlHelper(controller.ControllerContext.RequestContext)
        };

        ViewEngineResult result = ViewEngines
                                  .Engines
                                  .FindPartialView(controller.ControllerContext, partialName);

        if (result.View == null)
        {
            throw new InvalidOperationException(
            string.Format("The partial view '{0}' could not be found", partialName));
        }
        var partialPath = ((WebFormView)result.View).ViewPath;

        vp.ViewData.Model = model;

        Control control = vp.LoadControl(partialPath);
        vp.Controls.Add(control);

        var sb = new StringBuilder();

        using (var sw = new StringWriter(sb))
        {
            using (var tw = new HtmlTextWriter(sw))
            {
                vp.RenderControl(tw);
            }
        }
        return sb.ToString();
    }
}

usage:

....
string htmlBlock = this.RenderPartialToString("YourPartialView", model);
return htmlBlock;

i use this in a ton of controllers with 100% success...

jim

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.