Server side code in controller:
     public ContentResult TaskJsonP(string callback,int id)
        {
            var model = service.GetTaskDetails(new TaskDetailRequest() { Id = id });
            //return Json(model, JsonRequestBehavior.AllowGet);
            return Content(String.Format("{0}({1});",
          callback,
          new JavaScriptSerializer().Serialize(model)),          
          "application/javascript");

        }
Client side you can open any page and try below:
$.get("http://localhost:45897/home/taskJsonP/1",
                  
                   function(value)
                   {
                       alert (value)              },
                   "jsonp"
             );


 
Categories: Asp.net | C# | Html5 | JQuery | MVC

 Web Api:  vs2013 only
http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api#enable-cors
1. install cors package through package manager console
Install-Package Microsoft.AspNet.WebApi.Cors -pre -project WebService

2. Add to api cofig
 public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // New code
            config.EnableCors();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
3. enable on apiController
namespace WebService.Controllers
{
    [EnableCors(origins: "http://myclient.azurewebsites.net", headers: "*", methods: "*")]
    public class TestController : ApiController
    {
        // Controller methods not shown...
    }
}
4. some time you need $.support.cors = ture; before you make jsonp call



for WCF, congig it in webHttpbinding section of web.config:

 <webHttpBinding>
        <binding name="webHttpBindingWithJsonP" crossDomainScriptAccessEnabled="true" />
      </webHttpBinding>

If you use SignalR.
http://www.asp.net/signalr/overview/hubs-api/hubs-api-guide-javascript-client#crossdomain
var hubConfiguration = new HubConfiguration();
hubConfiguration.EnableCrossDomain = true;
RouteTable.Routes.MapHubs(hubConfiguration);

Client code that specifies a cross-domain connection (with the generated proxy)
$.connection.hub.url = 'http://fabrikam.com/'
$.connection.hub.start().done(init);

Client code that specifies a cross-domain connection (without the generated proxy)

var connection = $.hubConnection('http://fabrikam.com/');



 
Categories: JQuery | MVC | WCF

Tools-> Library Package Manager -> Package Manager Console

PM> Install-Package jQuery-vsdoc -Version 1.10.2
PM> Install-Package jquery.mobile
PM>
Install-Package Microsoft.AspNet.SignalR -Version 1.1.3
PM> Install-Package knockoutjs
PM> Install-Package Modernizr
PM> Install-Package jQuery.UI.Combined


 
Categories: JQuery | Visual studio 10/up

August 13, 2013
@ 10:12 AM
1. Config global to use WebApi in MVC4
 protected void Application_Start()
        {
            RouteTable.Routes.MapHubs();

            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

        }
2. Add your mapping in App_Start folder WebApiConfig.cs
public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
            config.Routes.MapHttpRoute(
             name: "GetTaskApi",
             routeTemplate: "api/{controller}/{action}/{id}/{token}",
             defaults: null
         );
            /*
             config.Routes.MapHttpRoute(
            name: "ApiById",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional },
            constraints: new { id = @"^[0-9]+$" }
        );

        config.Routes.MapHttpRoute(
            name: "ApiByName",
            routeTemplate: "api/{controller}/{action}/{name}",
            defaults: null,
            constraints: new { name = @"^[a-z]+$" }
        );

        config.Routes.MapHttpRoute(
            name: "ApiByAction",
            routeTemplate: "api/{controller}/{action}",
            defaults: new { action = "Get" }
        );
             */
        }
    }
3 Add you WebApi Controller
public class TaskController : ApiController
    {   
        // http://localhost:45897/api/task/1
        public TaskDetailResponse Get(int id)
                {
                    return  apiService.GetTaskDetails(new TaskDetailRequest(){Id=id});
                }
        // http://localhost:45897/api/task/gettask/1/testtoken
        public TaskDetailResponse GetTask([FromUri]TaskDetailRequest request)
        {
                    
            var response = apiService.GetTaskDetails(request);
            return response;
        }

    }

4. in Firefox and Chrome, if you visit the link, it will return xml, but in IE, it will let you save a json file



5. User jQuery.getJSON to call the api
function getData() {
        var apiUrl = 'api/task';
        var id = 1;
        $.getJSON(apiUrl + '/' + id)
            .done(function (data) {
                alert('ok!');
            })
            .fail(function (jqXHR, textStatus, err) {
                alert(err);
            });
    }


 
Categories: JQuery | MVC