ASP.NET MVC 3 JSONP: Does this work with JsonValueProviderFactory?

后端 未结 1 931
礼貌的吻别
礼貌的吻别 2020-11-29 06:18

Phil Haack has an excellent blog post on how to use JSON, data binding, and data validation.

Enter the browser\'s \"same origin policy security restriction.\" and JS

相关标签:
1条回答
  • 2020-11-29 06:55

    As far as receiving a JSON string and binding it to a model is concerned the JsonValueProviderFactory does this job out of the box in ASP.NET MVC 3. But there is nothing built-in for outputting JSONP. You could write a custom JsonpResult:

    public class JsonpResult : JsonResult
    {
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            var request = context.HttpContext.Request;
            var response = context.HttpContext.Response;
            string jsoncallback = (context.RouteData.Values["jsoncallback"] as string) ?? request["jsoncallback"];
            if (!string.IsNullOrEmpty(jsoncallback))
            {
                if (string.IsNullOrEmpty(base.ContentType))
                {
                    base.ContentType = "application/x-javascript";
                }
                response.Write(string.Format("{0}(", jsoncallback));
            }
            base.ExecuteResult(context);
            if (!string.IsNullOrEmpty(jsoncallback))
            {
                response.Write(")");
            }
        }
    }
    

    And then in your controller action:

    public ActionResult Foo()
    {
        return new JsonpResult
        {
            Data = new { Prop1 = "value1", Prop2 = "value2" },
            JsonRequestBehavior = JsonRequestBehavior.AllowGet
        };
    }
    

    which could be consumed from another domain with $.getJSON():

    $.getJSON('http://domain.com/home/foo?jsoncallback=?', function(data) {
        alert(data.Prop1);
    });
    
    0 讨论(0)
提交回复
热议问题