【问题标题】:In MVC3, what is the difference between the "JavaScript" and "Content" functions?在 MVC3 中,“JavaScript”和“Content”函数有什么区别?
【发布时间】:2011-05-29 20:06:42
【问题描述】:

在 ASP.NET MVC3 中,以下两种方法似乎返回相同的结果:

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

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

但是,当我在 Google Chrome 中查看第一个的结果时,字体是 Mono-Spaced 字体,而第二个是 Arial(或其他)。

这让我相信可能存在“text/javascript”的标题“内容类型”或某些东西...

那么我的问题是:

  • “JavaScript”函数(产生 JavaScriptResult)Content 方法(产生 ContentResult)没有做什么?

  • 这种方法有什么好处?

请不要包括宗教原因来解释为什么这种方法“不好”......我只关心知道“什么”......就像“它做了什么?”强>

【问题讨论】:

    标签: javascript asp.net-mvc-3 actionresult


    【解决方案1】:

    javascript actionresult 将 response.ContentType 设置为 application/x-javascript 其中内容 actionresult 可以通过调用其 ContentType 属性来设置。

    Javascript结果:

    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,并且您的结果将被发送到具有正确 ContentType 的客户端。

    【讨论】:

    • 你能包含一个实际的好处......例如“浏览器'xyz'不会执行JavaScript,除非你包含这个内容标题”或其他什么?
    • 这就是好处。客户端可以根据响应元数据做出决策。
    猜你喜欢
    • 2017-11-28
    • 2015-08-22
    • 2016-07-06
    • 2012-08-11
    • 2012-09-02
    • 2021-10-25
    • 2010-12-14
    • 1970-01-01
    相关资源
    最近更新 更多