1

ASP.NET MVC3 では、次の 2 つのメソッドは同じ結果を返すようです。

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

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

しかし、Google Chrome で最初の結果を表示すると、フォントは Mono-Spaced フォントですが、2 番目は Arial (または何か) です。

これにより、おそらく「text/javascript」のヘッダー「content-type」または何かがネットワークに渡っていると思われます...

私の質問はこれです:

  • 「JavaScript」関数 (JavaScriptResult を生成) は何を行い、Content メソッド (ContentResult を生成) は何を行いませんか?

  • この方法にはどのような利点がありますか?

この方法が「悪い」理由について宗教的な理由を含めないでください...私は「何を」知ることにのみ関心があります...「それは何をするのですか?」のように。

4

1 に答える 1

3

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);
        }
    }
}

利点は、これが JS であり、結果が正しい ContentType でクライアントに送信されることを MVC コードで明示していることです。

于 2011-05-29T23:08:58.597 に答える