2011-05-29 85 views
1

在ASP.NET MVC3,以下两种方法似乎返回相同的结果:在MVC3中,“JavaScript”和“Content”功能有什么区别?

public ActionResult Blah() 
{ 
    return JavaScript("alert('" + DateTime.Now + "');"); 
} 

public ActionResult Blah() 
{ 
    return Content("alert('" + DateTime.Now + "');"); 
} 

但是,当我认为谷歌浏览器的第一个结果,字体是单倍行距字体,而第二个是Arial(或某物)。

这使我相信,有可能是“文/ JavaScript的”什么的跨线未来的头“内容类型” ......

我的问题则是:

  • 什么是“JavaScript”函数(产生一个JavaScriptResult)do Content方法(产生一个ContentResult)不能做什么?

  • 这种方法有什么好处?

请,不包括宗教的原因,为什么这个方法是“坏” ......我只关心知道“是什么” ......在“它能做什么?”

回答

3

javascript actionresult将response.ContentType设置为应用程序/ x-javascript ,其中内容actionresult可以通过调用其ContentType属性进行设置。

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 。

+0

你可以包括一个实际的好处...比如“浏览器”xyz'不会执行JavaScript,除非你包含这个内容头“或什么的? – 2011-05-29 23:19:34

+0

这是好处。客户可以根据响应元数据做出决定。 – 2012-02-23 22:02:16

相关问题