I have created a Web API and in the same solution I have included another MVC project (Store App) and trying to consume the web api through jquery.ajax();
I am receiving a CROS issue. But If I add the dataType: "jsonp" then I do not receive CORS issue but in console log I see the below error:
SyntaxError: missing ; before statement
{"Id":1,"Name":"Prod1","Price":10.78}
I am not getting where actually to set the CORS property at IIS or in application (in Web API or MVC Internet application)?
If I am unable to call the Web API in same solution then how would it be able to call to other devices. Please let me know what I am lacking or missing.
Below is the code description
------------------------------------------------------------------------------------------------
Solution Name: WebAPI_Demo
1. MVC 4 Web API name : WebAPI_Demo
Code:
public class ProductController : ApiController
{
Product prd = new Product();
public Item Get(int id)
{
Item item = prd.AllProduct.Find(p => p.Id == id);
return item;
}
}
public class Product
{
public List<Item> AllProduct = new List<Item>();
public Product()
{
AllProduct.Add(new Item { Id = 1, Name = "Prod1", Price = 10.78 });
AllProduct.Add(new Item { Id = 2, Name = "Prod2", Price = 11.78 });
AllProduct.Add(new Item { Id = 3, Name = "Prod3", Price = 12.78 });
AllProduct.Add(new Item { Id = 4, Name = "Prod4", Price = 13.78 });
}
}
public class Item
{
public int Id { get; set; }
public string Name { get; set; }
public double Price { get; set; }
}
2. MVC 4 Internet Application name: StoreApp
Javascript on Item controller in StoreApp:
<script src="~/Scripts/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#btnGet").click(function () {
var id = $("#txtID").val();
var hitUrl = "http://localhost:38153/api/Product/" + id;
$.ajax({
url: hitUrl,
type: "GET",
data: "",
contentType: "application/json",
dataType: "jsonp",
success: function (data) {
console.log("Success");
console.log(data.Id);
console.log(data.Name);
console.log(data.Price);
},
error: function (e) {
console.log("Failure");
alert("error: " + e);
}
});
});
});
</script>