我正在使用此代码尝试将 Razor 部分 View 呈现为字符串,以便发送电子邮件。
public static string RenderPartialToString(
string userControlPath,
object viewModel,
ControllerContext controllerContext,
TempDataDictionary tempData)
{
using (var writer = new StringWriter())
{
var viewDataDictionary = new ViewDataDictionary(viewModel);
var view = new WebFormView(controllerContext, userControlPath);
var viewContext = new ViewContext(
controllerContext,
view,
viewDataDictionary,
tempData,
writer
);
viewContext.View.Render(viewContext, writer);
return writer.GetStringBuilder().ToString();
}
}
问题是我收到以下错误:
must derive from ViewPage, ViewPage<TModel>, ViewUserControl, or ViewUserControl<TModel>. Stack Trace: at System.Web.Mvc.WebFormView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) at .... RenderPartialToString
我该如何解决这个问题?
最佳答案
事实上,WebFormView
并不继承自上述类,而只是继承于 IView
。我做了一些谷歌研究并得到了一个可以运行的原型(prototype)。 This page是最有帮助的。
我创建了一个空的 MVC3 应用程序并创建了以下 HomeController
。当我运行应用程序时,页面显示渲染的字符串。 resultAsString
变量展示了如何将渲染捕获为字符串。
using System;
using System.IO;
using System.Web.Mvc;
public class HomeController : Controller
{
public ActionResult Index()
{
var result = RenderPartial(this.ControllerContext, "This is @DateTime.Now right now");
var resultAsString = result.Content;
return result;
}
private ContentResult RenderPartial(ControllerContext controllerContext, string template)
{
var temporaryViewPath = string.Format("~/Views/{0}.cshtml", Guid.NewGuid());
using (var stringWriter = new StringWriter())
{
using (var fileStream = System.IO.File.Create(Server.MapPath(temporaryViewPath)))
{
using (var streamWriter = new StreamWriter(fileStream))
{
streamWriter.WriteLine(template);
streamWriter.Close();
}
fileStream.Close();
}
var razor = new RazorView(controllerContext, temporaryViewPath, null, false, null);
razor.Render(new ViewContext(controllerContext, razor, new ViewDataDictionary(), new TempDataDictionary(), stringWriter), stringWriter);
System.IO.File.Delete(Server.MapPath(temporaryViewPath));
return Content(stringWriter.ToString());
}
}
}
关于string - ASP.NET MVC 将 Razor 部分 View 渲染为字符串错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11146862/