Search code examples
c#asp.net-mvc-4partial-views

How to get a partial view Html in the controller inside a folder?


I have a partial view named Form.cshtml in Shared folder. There is not any action and controller for it. It is in Shared folder and I just render it in a view named Index in Home controller.

All of codes I found needed a controller context but I do not have any controllers. So can I get the Html by the view physical address or any other way?


Solution

  • In Controller You must do like this

       public ActionResult GetPartial()
        {
          var viewStr=RenderRazorViewToString("~/Views/Home/Partial1.cshtml",new object())
          return content(viewStr);
        }
    
        // by this method you can  get string of view -- Update
        public string RenderRazorViewToString(string viewName, object model)
            {
                ViewData.Model = model;
                using (var sw = new StringWriter())
                {
                    var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext,
                                                                             viewName);
                    var viewContext = new ViewContext(ControllerContext, viewResult.View,
                                                 ViewData, TempData, sw);
                    viewResult.View.Render(viewContext, sw);
                    viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
                    return sw.GetStringBuilder().ToString();
                }