Render View programmatically into a string

前端 未结 3 1509
小鲜肉
小鲜肉 2020-12-30 14:51

I would like to get the html code a view would generate in a string, modify it in my controller, then add it to my JsonResult.

I found code that would do what i\'m t

3条回答
  •  萌比男神i
    2020-12-30 15:28

    This works like a charm (got it through SO).

    I use it like this:

    public class OfferController : Controller
    {
        [HttpPost]
        public JsonResult EditForm(int Id)
        {
            var model = Mapper.Map(_repo.GetOffer(Id));
    
            return Json(new { status = "ok", partial = this.RenderPartialViewToString("Edit", model) });
        }
    }
    
    
    
    public static partial class ControllerExtensions
    {
        public static string RenderPartialViewToString(this ControllerBase controller, string partialPath, object model)
        {
            if (string.IsNullOrEmpty(partialPath))
                partialPath = controller.ControllerContext.RouteData.GetRequiredString("action");
    
            controller.ViewData.Model = model;
    
            using (StringWriter sw = new StringWriter())
            {
                ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, partialPath);
                ViewContext viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
                // copy model state items to the html helper 
                foreach (var item in viewContext.Controller.ViewData.ModelState)
                    if (!viewContext.ViewData.ModelState.Keys.Contains(item.Key))
                    {
                        viewContext.ViewData.ModelState.Add(item);
                    }
    
    
                viewResult.View.Render(viewContext, sw);
    
                return sw.GetStringBuilder().ToString();
            }
        }
    }
    

提交回复
热议问题