mamu
mamu

Reputation: 12414

MVC View html ouput in json

Probably this has been asked so many times before but i can't find answer any where.

I have a Action

public ActionResult SearchResult()
{
   return View();
}

Now i need some data as well which is related to View, so i am trying to do following

public JsonResult SearchResult()
{
   var result = new JsonResult();

   result.Data = new { Data = x, Html = "Here i need html generated from view" }

   return result;
}

How can i get html generated from my view? i can also convert it to control if required.

Upvotes: 1

Views: 307

Answers (2)

Alexander Prokofyev
Alexander Prokofyev

Reputation: 34515

I such case I use an Controller class extension inspired by the article http://craftycodeblog.com/2010/05/15/asp-net-mvc-render-partial-view-to-string/

public static class ControllerHelper
{
    public static string RenderPartialViewToString(this Controller controller, 
        string viewName, object model)
    {
        if (string.IsNullOrEmpty(viewName))
            viewName = controller.ControllerContext.RouteData.
                GetRequiredString("action");

        controller.ViewData.Model = model;

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

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

Upvotes: 1

Russ Cam
Russ Cam

Reputation: 125488

What data do you need specifically? In theory, I would think that most of the data that you would want would come from your Model and thus accessible in the Controller action.

If it's a block of HTML that you need, perhaps extract it's generation out to a method that you can call in both your view and controller action. This could take the form of a HtmlHelper if the outputted HTML uses values from the model.

Upvotes: 0

Related Questions