【发布时间】:2012-10-10 03:00:07
【问题描述】:
我必须在 ASP.NET MVC 视图的 IFrame 中呈现 html。我将视图中 iframe 的“源”设置为“控制器操作”。但是,我没有看到嵌入在我的视图中的实际 html,而是看到了 html 源代码和 html 文本中的一些特殊字符。我在这里有一个相同的屏幕截图: https://plus.google.com/photos/117026675016318325824/albums/5797507243229043425?banner=pwa&gpsrc=pwrd1#photos/117026675016318325824/albums/5797507243229043425?banner=pwa&gpsrc=pwrd1 我还想补充一点,一个 pdf 文档和一个文本文档使用相同的代码可以很好地呈现,只有呈现 html 文档是一个问题。
如何让视图以正确的格式显示 html?
控制器:
public BinaryNonBinaryActionResult GetAgreement(string id)
{
string agreementText = "<FONT color=deepskyblue><STRONG> test text</STRONG></FONT>";
return new BinaryNonBinaryActionResult(GetBytes(agreementText), "text/html");
}
static byte[] GetBytes(string str)
{
byte[] bytes = new byte[str.Length * sizeof(char)];
Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
public class BinaryNonBinaryActionResult : ActionResult
{
private byte[] bytes;
private string contentType ;
public BinaryNonBinaryActionResult(byte[] bytes, string contentType)
{
this.bytes =bytes;
this.contentType = contentType;
}
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
throw new ArgumentNullException("context");
var response = context.HttpContext.Response;
response.ContentType = contentType;
var imageStream = new MemoryStream(bytes);
var buffer = new byte[4096];
while (true)
{
var read = imageStream.Read(buffer, 0, buffer.Length);
if (read == 0)
break;
response.OutputStream.Write(buffer, 0, read);
}
response.End();
}
}
【问题讨论】:
-
我通过将代码更改为来解决此问题: public BinaryNonBinaryActionResult GetAgreement(string id) { string agreementText = " test text"; return new BinaryNonBinaryActionResult(Encoding.ASCII.GetBytes(agreementText), "text/html"); }。感谢@Sathish 指出这一点。
标签: c# asp.net-mvc iframe