재우니의 블로그


 ASP.NET MVC 3 로 구현된 부분이며, 이는 JSONP 를 통해 타 도메인간의 데이터를 교환하는 방법에 대해 기술한 부분이다.



$(function () {
        $.ajax({
            dataType: 'jsonp',
            url: 'http;//otherdomain.com/Home/GetEmployees'//Normally this would be a url to an application on a different domain for JSONP
            success: function (data) {                
                var viewModel = {
                    FirstName: ko.observable(data[0].FirstName),
                    LastName: ko.observable(data[0].LastName),
                    Address: ko.observable( data[0].Address),
                    City: ko.observable (data[0].City),
                    Region: ko.observable(data[0].Region)
                };
                ko.applyBindings(viewModel);
               
            }
        });
    });


이는 JSONP 의 데이터를 반환처리 하는 부분이다. ActionResult 클래스의 JsonpResult 에서 생성한다.


using System;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;

namespace JSONPExample.ActionResults
{
    public class JsonpResult : ActionResult
    {
         public string CallbackFunction { get; set; }
         public Encoding ContentEncoding { get; set; }
         public string ContentType { get; set; }
         public object Data { get; set; }
        public JsonpResult(object data) : this(data, null) { }
        public JsonpResult(object data, string callbackFunction)
        {
            Data = data;
            CallbackFunction = callbackFunction;
        }

        public override void ExecuteResult(ControllerContext context)
         {
             if (context == null) throw new ArgumentNullException("context");
            HttpResponseBase response = context.HttpContext.Response;
            response.ContentType = string.IsNullOrEmpty(ContentType) ? "application/x-javascript" : ContentType;

             if (ContentEncoding != null) response.ContentEncoding = ContentEncoding;
             if (Data != null)
            {
                HttpRequestBase request = context.HttpContext.Request;
                var callback = CallbackFunction ?? request.Params["callback"] ?? "callback";
                var serializer = new JavaScriptSerializer();
                 response.Write(string.Format("{0}({1});", callback, serializer.Serialize(Data)));
             }
         }
    }
}



이제 GetEmployees 메소드를 통해 호출한 jQuery 에서 Employee 제네릭 객체들을 가져와서 객체를 jsonP 에 맞게 출력하여 반환한다.


public ActionResult GetEmployees()

        {
            var data =  GetDataSomehow();
             //constructor overload for overriding callback function:
            //return new JsonpResult(data, "callback function");
           return new JsonpResult(data);
        }

        private List<Employee> GetDataSomehow()
         {
             // Surrogate for getting some data from your database or other store
            List<Employee> emps = new List<Employee>();
            Employee emp = new Employee()
                               {
                                   Address = "123 High st.",
                                   BirthDate = DateTime.Parse("2/2/1980"),
                                   FirstName = "Joe",
                                   LastName = "Blow",
                                   City = "Yuma",
                                   Region ="AZ",
                                   Country = "US",
                                   EmployeeID = 1,
                                   HomePhone = "999-999-9999"
                               };
            emps.Add(emp);
            return emps;
        }


발췌 : http://www.eggheadcafe.com/tutorials/asp-net/346046ca-d54b-4ab3-b9f1-ccdf4262bcfb/handling-jsonp-requests-in-aspnet-mvc-3.aspx