views:

28

answers:

2

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.

A: 

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.

Russ Cam
+1  A: 

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();
        }
    }
}
Alexander Prokofyev
We used to use this, but MVC 2 does not like it. We were actually using it to return results with a pager. It was very sluggish in the end, and we switched to using Ajax.BeginForm so that we could upgrade our app to MVC 2.0.
Josh