asp.net mvc 3-在MVC3中;JavaScript”;以及“;“内容”;功能
asp.net mvc 3 - In MVC3, what is the difference between the "JavaScript" and "Content" functions?
在ASP.NET MVC3中,以下两个方法似乎返回相同的结果:
public ActionResult Blah()
{
return JavaScript("alert('" + DateTime.Now + "');");
}
public ActionResult Blah()
{
return Content("alert('" + DateTime.Now + "');");
}
但是,当我在Google Chrome中查看第一个的结果时,字体是Mono-Spaced字体,而第二个是Arial(或其他什么)。
这让我相信,可能有一个标题"content-type"为"text/javascript"或其他什么。。。
我的问题是:
"JavaScript"函数(产生JavaScriptResult)做了什么而Content方法(产生ContentResult)没有做什么
这种方法有什么好处?
请不要将宗教原因包括在内,说明为什么这种方法"不好"。。。我只关心知道"什么"。。。如"它做什么?"
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);
}
}
}
}
ContentResult
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,并且您的结果是使用正确的ContentType发送到客户端。