我正在开发一个ASP.NET MVC应用程序,它将向用户发送一封确认电子邮件。对于电子邮件本身,我想创建一个视图,然后呈现该视图,并使用.NET邮件对象发送它。
我如何使用MVC框架来做这件事?
发布于 2009-09-04 03:47:16
根据我对Richard的回答的评论,这段代码确实可以工作,但它总是导致“发送HTTP报头后无法重定向”错误。
在对Google进行了大量挖掘并感到沮丧之后,我终于在这篇文章中找到了一些似乎能做到这一点的代码:
http://mikehadlow.blogspot.com/2008/06/mvc-framework-capturing-output-of-view_05.html
这家伙的方法是创建他自己的HttpContext。
而不是使用MVCContrib BlockRenderer,我只是将当前的HttpContext替换为一个新的a,它承载了一个写入StringWriter的响应。
这个方法工作得很好(一个小的区别是我必须创建一个单独的Action来渲染我的局部视图,但没有戏剧性的效果)。
发布于 2009-03-04 09:09:10
您基本上需要使用IView.Render。您可以通过使用ViewEngineCollection.FindView (默认值为ViewEngines.Engines.FindView)来获取视图。将输出呈现为TextWriter,并确保在之后调用ViewEngine.ReleaseView。示例代码如下(未经测试):
StringWriter output = new StringWriter();
string viewName = "Email";
string masterName = "";
ViewEngineResult result = ViewEngines.Engines.FindView(ControllerContext, viewName, masterName);
ViewContext viewContext = new ViewContext(ControllerContext, result.View, viewData, tempData);
result.View.Render(viewContext, output);
result.ViewEngine.ReleaseView(ControllerContext, result.View);
string viewOutput = output.ToString();我将把viewData / tempData留给您。
发布于 2013-11-12 11:37:57
这对我很有效:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
namespace Profiteer.WebUI.Controllers
{
public class SampleController : Controller
{
public ActionResult Index()
{
RenderViewAsHtml(RouteData.Values["controller"].ToString(),
RouteData.Values["action"].ToString());
return View();
}
private void RenderViewAsHtml(string controllerName, string viewName)
{
var vEngine = (from ve in ViewEngineCollection
where ve.GetType() == typeof(RazorViewEngine)
select ve).FirstOrDefault();
if (vEngine != null)
{
var view =
vEngine.FindView(
ControllerContext,
viewName, "_Layout", false).View as RazorView;
if (view != null)
{
var outPath =
Server.MapPath(
string.Format("~/Views/{0}/{1}.html",
controllerName, viewName));
using (var sw = new StreamWriter(outPath, false))
{
var viewContext =
new ViewContext(ControllerContext,
view,
new ViewDataDictionary(),
new TempDataDictionary(),
sw);
view.Render(viewContext, sw);
}
}
}
}
}
}https://stackoverflow.com/questions/609772
复制相似问题