Using JSONP calls in ASP.NET MVC

Using JSONP calls in ASP.NET MVC

Using JSONP calls in ASP.NET MVC

JSONP is the technique of making cross-domain HTTP requests via JavaScript circumventing browser security restictions on requests that return data in the JSON format.

By cross-domain, we refer to the practice of making HTTP requests on URLs that refer to resources residing on a domain other than the one from where the page being viewed/executed was loaded from.

What is the JSONP

Simply telling JSONP (JSON with Padding) was created as a workaround to the cross domain problem. The cross domain problem refers to the fact that Ajax code run from website A can't access data from website B.

Take a look on the following example. For our company we wanted to create one unique landing page for all of our under maintenance projects. Basically we wanted to create one simple HTML page with the newsletter and contact form.

The problem occured when I tried to figure it out how to send data from one server to another. Previously in the past, for this case scenario, I would send JSON data via web service, but now I wanted to try some different approach.

How to use JSONP in ASP.NET MVC?

In JSONP, the remote resource doesn't return plain data to the caller. It returns the data by wrapping it in a JavaScript function call. The JavaScript function name is usually supplied by the caller. The page making the request contains that function. Just to make this concept clear, consider the following example.

Lets take a look of our basic newsletter form that we created for this example. It contains one input email field and one submit input field. Our goal is to send via ajax, using JSONP, an email address to remote server.

<div id="subscribe">
	
	<form onSubmit="return false;" method="post">
	
		<label>Subscribe</label>
	
		<input type="text" id="email" name="email" value="" placeholder="Please Enter To Your E-Mail Address" />
		
		<input type="button" value="Subscribe"  />
	
	</form> 

</div>

Using jQuery for Making JSONP Requests

When users clicks on the submit button, he will invoke JSONP request and sent data to remote server. You can see on below example that main difference, between invoking JSON and JSONP request, is that you need to specify dataType as “jsonp” instead of “json” and the callback query string parameter jsonp to specify as “callback” using the jsonp option .

$('#subscribe input[type="button"]').live('click', function() {
		
	var serviceSubscribeUrl = 'http://www.yourdomain.com/Home/Controller/Action';

	email = $("#email").val(); 
	var data = { Email: email };
	
	$.ajax({
		url: serviceSubscribeUrl,
		data: data,
		type: "GET",
		dataType: "jsonp",
		jsonp: "callback",
		success: function (data) {
			// implement your code here
		},
		error: function (XMLHttpRequest, textStatus, errorThrown) {
			alert(errorThrown);
		}
	});  	
	
});

How to return JSONP data using ASP.NET MVC

First we will need to create a new custom action result class JsonpResult that derives from the JsonResult class. The JsonResult class is an inbuilt class provided by ASP.NET MVC and represents the data in JSON format. Lets take a look of our JsonpResult class that we will use in our later example.

namespace Ingenium.Web
{
    public class JsonpResult : JsonResult
    {
        object Data = null;

        public JsonpResult()
        {
        }

        public JsonpResult(object Data)
        {
            this.Data = Data;
        }

        public override void ExecuteResult(ControllerContext ControllerContext)
        {
            if (ControllerContext != null)
            {
                HttpResponseBase Response = ControllerContext.HttpContext.Response;
                HttpRequestBase Request = ControllerContext.HttpContext.Request;

                string callbackfunction = Request["callback"];
                if (string.IsNullOrEmpty(callbackfunction))
                {
                    throw new Exception("Callback function name must be provided in the request!");
                }
                Response.ContentType = "application/x-javascript";
                if (Data != null)
                {
                    JavaScriptSerializer serializer = new JavaScriptSerializer();
                    Response.Write(string.Format("{0}({1});", callbackfunction, serializer.Serialize(Data)));
                }
            }
        }
    }
}

The parameterized constructor of the JsonpResult class accepts an object that represents the data to be wrapped in JSONP form.

The ExecuteResult() method is where all the main logic goes. The code first grabs a query string parameter named callback which holds the name of the JavaScript function acting as a callback. ;

For our latest step, the only thing left to do is to create custom action method SubscribeToNewsletter. The SubscribeToNewsletter() method is shown below:

public JsonpResult SubscribeToNewsletter(string Email)
{
	string message = String.Empty;
	// Implement your code here
	JsonpResult result = new JsonpResult(message);
	return result;
}

The SubscribeToNewsletter() method accepts one string parameter - Email - that represents a newsletter subscriber email. The return type, if SubscribeToNewsletter() method, is JsonpResult.

Browsers don't let you make cross-domain requests due for security reasons, but if you want to do it anyway use JSON with Padding or JSONP. Using JSONP you can achieve cross-domain communication in legitimate scenarios.

Posted by Ingenium Llc.

Ingenium Llc.

iNGENIUM Llc. is an software development company from EU which delivers a full range of custom .NET, web and mobile solutions for different business to meet partner's demand.

The Power of Imagination Makes Us Infinite

Related Posts

Comments

comments powered by Disqus