0

Let's assume I have 3 custom controllers: AController, BController and CControler and one default HomeController. Each of the first three controllers have a very unique partial view for them, let's name them APartial, BPartial, CPartial and these are invoked with AFunction, BFunction and CFunction with a template looking like:

public ActionResult XFunction
{
    /*put some data into a ViewBag*/
    return PartialView("XPartial");
}

Respectivelly, APartial.cshtml, BPartial.cshtml, CPartial.cshtml are in the Shared folder. What is the best way to return all three views in one page when HomeController's Index (ActionResult method) is called. I tried rendering each like:

using (StringWriter sw = new StringWriter())
{
    ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, "XFunction");
    ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
    viewResult.View.Render(viewContext, sw);

    return MvcHtmlString.Create(sw.GetStringBuilder().ToString());
}

then putting each into ViewBag's dynamic variables, but I have a feeling there has to be a way nicer solution.

5
  • can't you just put all three of them in a view? Commented Apr 7, 2013 at 8:22
  • No, I would like to reuse them in other places. Commented Apr 7, 2013 at 8:39
  • I mean in another view that renders all three partials like so: @Html.Partial('partialview1') @Html.Partial('partialview2') @Html.Partial('partialview3') Commented Apr 7, 2013 at 8:43
  • The problem is, I am calling this async and I cannot write @Html.Partial, because I replace my main div with the result, so either: I cannot do that OR I overlooked being able to call @Html.Partial inside my Home/Index.cshtml. I am going to try that. I'll let you know asap. Commented Apr 7, 2013 at 9:03
  • RenderAction did the trick, but it was basically the same idea as you told, I think :) Thanks a lot :) Commented Apr 7, 2013 at 11:09

1 Answer 1

1

Use RenderAction in your view. Good explanation is here: http://www.arrangeactassert.com/when-to-use-html-renderpartial-and-html-renderaction-in-asp-net-mvc-razor-views/

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

1 Comment

RenderAction did the trick. Thanks for saving me!!! :) Now it is so much easier to handle everything.

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.