Duy Tran
Duy Tran

Reputation: 85

Using MVC 4 as Web Service

I'm now trying to build a web service based on MVC 4 and client using HTML. The problem is my HTML file is put outside the application and my MVC service is running on Visual Studio IIS Express. I don't know if it causes my problem or because of any missing anything in Web.config.

Here is my code of Index method inside my Controller:

public ActionResult Index() {
    return Content("It works");
}

And this is my code in client side:

$.ajax({
    url: 'http://localhost:54502/<MyControllerName>/Index',
    type: 'POST',
    datatype:"JSON",
    contentType:"application/json; charset=utf-8",
    success: function(data) {
        alert(data);
    },
    error: function(data) {
        alert("error");
    },
        complete: function(jqXHR,status) {          
    }
});

The problem is it always alert out "error" and nothing seems to work. Any help would be highly appriciated!

Upvotes: 0

Views: 493

Answers (2)

Duy Tran
Duy Tran

Reputation: 85

I figured out my solution and it related to Cross-Domain problem. I use WebAPI and install CORS package using NuGet and now I can access the web service via ajax call even outside my localhost domain.

Upvotes: 1

garethppls
garethppls

Reputation: 36

The content isn't serialised as JSON. If it is HTML it is going to be of content-type text/html rather than application/json.

I'd recommend using WebAPI or WCF's WebHttpBinding for this.

Upvotes: 2

Related Questions