0
votes

I'm working on a MVC project where the Views and Controllers are on different projects within my solution.

The problem I'm trying to solve is this: I have an action which should return a Json with some information and an Html String.

This Html string is already inside a partial view. This partial is not returned in particular by any action in any controller. It is called inside another view.

So, I read that using HtmlHelper inside a controller is not good practice. However, if I don't do it, I will have duplicated html (partial view and as a string on this particular action).

What I want is to render a view to a string, allowing me to have the html centralized on the view. Once I have the view rendered as a string, I can return it as an attribute of the json object returned.

As I said, the controllers are in a different project, already referencing System.Web.Mvc. But once I type "HtmlHelper." the "Partial" method is not within the options. For some season, even though the System.Web.Mvc.Html.PartialExtensions are within reach, Visual Studio won't let me use it.

Is there a different way to solve this problem without using HtmlHelper inside the controller?

And can Visual Studio filter methods based on where it is going to be used? Or am I missing some reference?

Ps.: I'm using Visual Studio 2010, .Net Framework 4, Asp.Net MVC 4.

Thanks in advance.

1

1 Answers

1
votes

It sounds like you want to render a partial view as a string and return it as part of a JSON response. The following method will allow you to do that

protected string PartialViewAsString(string partialviewName, object model)
{
    if (string.IsNullOrEmpty(partialviewName))
    {
        partialviewName = ControllerContext.RouteData.GetRequiredString("action");
    }

    var viewData = ViewData;   
    ViewData = new ViewDataDictionary(viewData) { Model = model };

    using (var writer = new StringWriter())
    {
        var viewResult = ViewEngineCollection.FindPartialView(ControllerContext, partialviewName);
        var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, writer);
        viewResult.View.Render(viewContext, writer);
        ViewData = viewData;

        return writer.ToString();
    }
}

Implement it either on the controller in question or on a base controller from which you derive your controllers from.