Reputation: 2973
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?
Upvotes: 2
Views: 9126
Reputation: 3763
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();
}
Upvotes: 6
Reputation: 728
all you need to specify full path to view
@Html.Partial("/Views/Shared/Form.cshtml")
https://stackoverflow.com/a/2759898/4104866 you can use this to render any partial to string,a i think any controller context will be work ,because of using full path to view
Upvotes: 3