我需要将ASP.MVC 3 View()的HTML输出保存为可以发送到其他Web服务的字符串。当我调用“return view()”时,它显然会将输出呈现给屏幕。我只是想把它捕获到一串HTML。可能的?
答案 0 :(得分:1)
您可以使用ViewContext让MVC框架将视图呈现给TextWriter类,如StringWriter,然后从该对象中检索呈现的字符串。
public string RenderViewToString(ControllerContext context, ViewResultBase viewBase)
{
using (var sw = new StringWriter())
{
var view = viewBase.View;
var viewContext = new ViewContext(context, view, viewBase.ViewData,
viewBase.TempData, sw);
view.Render(viewContext, sw);
return sw.ToString();
}
}
答案 1 :(得分:-1)
创建一个控制器,可以根据需要呈现html视图。不要在视图的html中包含任何你不想要的字符串
public ActionResult HtmlView()
{
return View();
}
public static string GetContent(string templatePath, string queryString = "")
{
bool isLocal = false;
if (HttpContext.Current != null)
isLocal = HttpContext.Current.Request.IsLocal;
try
{
var objWebClient = new System.Net.WebClient();
byte[] requestedHtml;
if (isLocal)
{
string path = "http://" + HttpContext.Current.Request.ServerVariables["SERVER_NAME"] + ":" +
HttpContext.Current.Request.ServerVariables["SERVER_PORT"] + templatePath +
queryString;
requestedHtml = objWebClient.DownloadData(path);
}
else
{
requestedHtml = objWebClient.DownloadData("http://" + HttpContext.Current.Request.ServerVariables["SERVER_NAME"] + templatePath + queryString);
}
var utf8 = new UTF8Encoding();
return utf8.GetString(requestedHtml).Replace(Environment.NewLine, "");
}
catch (Exception e)
{
return "";
}
}
在您的代码中,您可以调用
string newString = GetContent("/Controller/HtmlView");