0

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!

2
  • 1
    Have you tried navigating to the URL in your webbrowser? What do you see? Commented Sep 2, 2013 at 15:37
  • It's totally fine and returns exactly the String "It works" Commented Sep 2, 2013 at 15:38

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

8 Comments

My intention is to use Json format, such as return Json(new Object[] { "success", returnObj }, JsonRequestBehavior.AllowGet); But it didn't work so i have to write simple test case as above and it doesn't seem to work, either.
If you look at the response in Fiddler2 or some other tool you'll see that the message will have content-type html. You should consider using WebAPI which is built for webservices, or WCF's WebHttpBinding which can automatically serialise your objects into JSON or XML for consumption.
Is there no way to write a web service with MVC 4?
WebAPI is an extension of ASP.NET MVC 4. (asp.net/web-api). Different tools are best used in different situations. Luckily C# and ASP.NET give us that selection. Knowing when to use what is important.
I found out my solution. I will update my answer below, thanks for your help.
|
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.