在MVC3中,“";JavaScript";及;内容“;功能?
在ASP.NET MVC3中,以下两种方法似乎返回相同的结果:在MVC3中,“";JavaScript";及;内容“;功能?,javascript,asp.net-mvc-3,actionresult,Javascript,Asp.net Mvc 3,Actionresult,在ASP.NET MVC3中,以下两种方法似乎返回相同的结果: public ActionResult Blah() { return JavaScript("alert('" + DateTime.Now + "');"); } public ActionResult Blah() { return Content("alert('" + DateTime.Now + "');"); } 但是,当我在Google Chrome中查看第一个的结果时,字体是单间距字体,而第二个
public ActionResult Blah()
{
return JavaScript("alert('" + DateTime.Now + "');");
}
public ActionResult Blah()
{
return Content("alert('" + DateTime.Now + "');");
}
但是,当我在Google Chrome中查看第一个的结果时,字体是单间距字体,而第二个是Arial(或其他)
这让我相信,可能有一个标题“内容类型”为“text/javascript”,或者其他什么东西出现在网络上
那么,我的问题是:
- “JavaScript”函数(生成JavaScriptResult)做了什么而Content方法(生成ContentResult)没有做什么?
- 这种方法有什么好处
请不要将宗教原因包括在内,以解释为什么这种方法“不好”。。。我只关心知道“什么”。。。与“它做了什么?”一样,javascript actionresult将response.ContentType设置为application/x-javascript 其中,可以通过调用其ContentType属性来设置内容actionresult JavascriptResult:
using System;
namespace System.Web.Mvc
{
public class JavaScriptResult : ActionResult
{
public string Script
{
get;
set;
}
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
HttpResponseBase response = context.HttpContext.Response;
response.ContentType = "application/x-javascript";
if (this.Script != null)
{
response.Write(this.Script);
}
}
}
}
内容结果
public class ContentResult : ActionResult
{
public string Content
{
get;
set;
}
public Encoding ContentEncoding
{
get;
set;
}
public string ContentType
{
get;
set;
}
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
HttpResponseBase response = context.HttpContext.Response;
if (!string.IsNullOrEmpty(this.ContentType))
{
response.ContentType = this.ContentType;
}
if (this.ContentEncoding != null)
{
response.ContentEncoding = this.ContentEncoding;
}
if (this.Content != null)
{
response.Write(this.Content);
}
}
}
好处是您在MVC代码中明确表示这是JS,并且您的结果将以正确的内容类型发送到客户端。您是否可以包括实际的好处。。。例如“浏览器‘xyz’将不会执行JavaScript,除非您包含此内容标题”或其他内容?这就是好处。客户机可以根据响应元数据做出决策。