Reputation: 886
This is the first time I am using the Web API component in MVC 4. I just created a Web API project to manage a person details. I wrote a get function in Person Controller and called it from browser. The result is:
<ArrayOfPerson xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/WebAPITest.Models">
<Person>
<Address>Addr</Address>
<DOB>2013-05-04T00:00:00</DOB>
<ID>1</ID>
<Name>Name</Name>
</Person>
</ArrayOfPerson>
The URL is: http://localhost:3802/api/Person
Then I added a new MVC basic project to the solution and tried to call the Web API from the view page. The code in view page is :
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script src="~/Scripts/jquery-1.7.1.js"></script>
<script>
$(document).ready(function () {
$.ajax({
url: "http://localhost:3802/api/Person",
type: "Get",
success: function (data) {
for (var i = 0; i < data.length; i++) {
$("<tr></tr><td></td>" + data[i].Name + "</td><td></td>" + data[i].Address + "</td><td></td>" + data[i].DOB + "</td></tr>").appendTo("#tbPerson");
}
},
error: function (msg) { alert("Error"); }
});
});
</script>
<h2>Index</h2>
<table id="tbPerson">
<tr>
<th>Name</th>
<th>Address</th>
<th>DOB</th>
</tr>
</table>
But I am getting the alert box showing the Error. Can anyone help me out?
Upvotes: 0
Views: 222
Reputation: 11601
Try to change url: "http://localhost:3802/api/Person"
to
url: "/api/Person"
Upvotes: 0
Reputation: 19321
Since you added a new MVC project, it will run in a port other than 3802. So, the page URI will be something like http://localhost:<someport>/home/index
. If JavaScript from this page calls the URI of your API endpoint, which is http://localhost:3802/api/Person
, the request becomes a cross-origin request and browser does not allow it. For more info, take a look at http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api. There is a great MSDN article by Brock Allen on this topic - http://msdn.microsoft.com/en-us/magazine/dn532203.aspx.
Upvotes: 1