Here I have one of the best and alternate solutions for your problems which will work both view and PartialView. It means with or without Layout in Views. Given solutions exactly return string which you have implemented in your methods. I have already posted this solutions at https://stackoverflow.com/a/18978036/2318354. Now here I will explain in details with Controller, Views and Models.
First of create one class with following methods.
public static class RazorViewToString
{
public static string RenderRazorViewToString(this Controller controller, string viewName, object model)
{
if (controller == null)
{
throw new ArgumentNullException(nameof(controller), "The parameter controller cannot be null.");
}
if (controller.ControllerContext == null)
{
return string.Empty;
}
controller.ViewData.Model = model;
using (var sw = new StringWriter())
{
var viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
var viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
viewResult.View.Render(viewContext, sw);
viewResult.ViewEngine.ReleaseView(controller.ControllerContext, viewResult.View);
return sw.GetStringBuilder().ToString();
}
}
}
Now create one simple Model name it as Test.cs
public class Test
{
public string Name { get; set; }
}
Your Controller should be like this
public ActionResult Index()
{
Test test = new Test();
test.Name = "XYZ";
string html = RazorViewToString.RenderRazorViewToString(this, "~/Views/Test/index.cshtml", test);
return View();
}
Now even in your Views you use Layout or not it will work fine as your View may be like this
@model W2G.Models.Test
@using W2G.App_GlobalResources;
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
This is test @Model.Name
So above solutions will return exact you want from your Razor.Parse
I hope it will help you.