Cross Origin Resource Sharing in MVC 4 using JSONP

Hi, In the below post we will learn how to extend MVC framework to support jsonp requests.

JSONP(JSON with Padding) is a technique of sending and receiving cross domain resources .

here I am going to explain how you can use the JSONP for cross domain requests. Next I have created a MVC4 project “NorthwindProject”using Northwind sample database as backend , where I am using the entity Framework to accessing the data.

Now, JSONP is not directly supported by MVC framework so first You have to create custom Result class which will handle the JSONP as well as normal request as below

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace NorthwindProject.Custom
{
public class CustomActionResult : JsonResult
{
public CustomActionResult()
{
JsonRequestBehavior = System.Web.Mvc.JsonRequestBehavior.AllowGet;
}
public override void ExecuteResult(ControllerContext context)
{

HttpContextBase httpContext = context.HttpContext;
string callBackFunction = string.Empty;
// Check if callback function provided or not;
if (string.IsNullOrWhiteSpace(httpContext.Request["callback"]) == false)
{
callBackFunction = httpContext.Request["callback"];
}
if (string.IsNullOrEmpty(callBackFunction) == false)
{
// jsonp request
httpContext.Response.Write(callBackFunction + " (");
base.ExecuteResult(context);
httpContext.Response.Write(" );");
}
else
{
//normal process
ViewResult v = new ViewResult();
v.ViewBag.Model = Data;
v.ExecuteResult(context);
}
}
}
}

 

In the above code the CustomActionResult is inherited from the JSONResult and the ExecuteResult function has a logic to check whether the request is JSONP request or not by checking that “callback” parameter, The JSONP requests pass the callback function.

 

Now below is the code updated to serve both request

public ActionResult Index()
{
db.Configuration.ProxyCreationEnabled = false;
var customerList = db.Customers.ToList(); ;
return new CustomActionResult { Data = customerList };
// return View(db.Customers.ToList());
}

 

In this code I am using CustomActionResult to serve the request.Now below is the code updates for the cshtml which will serve normal request.

 


Index




@Html.ActionLink("Create New", "Create")




@{

var grid = new WebGrid(ViewBag.Model, defaultSort: "CompanyName");
}
@grid.GetHtml(
columns: grid.Columns(
grid.Column("CustomerID", "Customer ID"),
grid.Column("CompanyName", "Company Name"),
grid.Column("ContactName", "Contact Name")
)
)

In the above code I am using WebGrid to display the customer data. you can see that I am passing ViewBag.Model as a Model data. Now if the request is not JSONP request and from the same domain then it will work as normal .

image

Now I am creating another project “NorthwindClient” which will send the jsonp request and fetch data. I have created a cshtml view which is sending ajax request to another domain as below

@{
ViewBag.Title = "Customer List";
}

Index

@section scripts {
<script type="text/javascript">
function showCustomerList(data) {
var customerTable;
if (data) {
customerTable = "";
customerTable+=""
for (var i = 0; i < data.length; i++) {
customerTable += "";
customerTable += "";
customerTable += "";
customerTable += "";
customerTable += "";
}
customerTable += "
Customer IDCompany NameContact Name
" + data[i]["CustomerID"] + "" + data[i]["CompanyName"] + "" + data[i]["ContactName"] + "
"
;

}

$($.find("#customerList")).append(customerTable);
}

$.ajax({
type: 'GET',
url: "http://localhost:49416/customer",
async: false,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function (data) {
showCustomerList(data);
},
error: function (e) {
console.log(e.message);
}
});


}
<div id="customerList" >

In the above code you can see that url of another domain in ajax request . if the execution succeed then it will comes to “success” function and then execute the “showCustomerList” function which is rending a table and later appending it to the div named “customerList”. after execution you will get the below output.

image 

We just developed the working solution , Hope you find this post useful . Thanks for reading. 🙂
Advertisements