I tried to make ASP.NET Web Api CRUD operation in VS 2010 web application, but why the result is not returning all entire row from source table.
This is my code :
Route/Globax.asax
protected void Application_Start(object sender, EventArgs e)
{
RouteTable.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}", // browse with localhost:7031/api/product
//routeTemplate: "{controller}/{id}", // browse with localhost:7031/product
defaults: new { id = System.Web.Http.RouteParameter.Optional }
);
Controller/ProductController.cs :
public class ProductController : ApiController
{
NorthwindEntities db = new NorthwindEntities();
public List<Product> GetAll()
{
return db.Products.ToList<Product>();// ;
}
View/ViewProduct.aspx :
<script src="Script/jquery-1.7.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$('#<%= cviewproduct.ClientID %>').click(function (e) {
getProducts();
e.preventDefault();
});
});
function getProducts() {
$.getJSON("/api/product",
function (data) {
$.each(data, function (key, val) {
//var str = val.ProductName;
// alert(str);
var row = '<tr> <td>' + val.ProductName + '</td><td>' + val.ProductID + '</td><tr/>';
$(row).appendTo($('#tblproduct'));
});
});
}
</script>
Bellow Is The Result of product Controller via 'http://localhost:7031/api/product' :

Bellow Is The Result of getProducts() function :

Please help me.
Any idea or suggestion ?
When you execute $.getJSON("/api/product", ...
, you are not getting back XML as you posted. You are getting back JSON.
As a first step, I suggest you download and install Fiddler2. Open it, and use the Composer tab to execute a GET for http://localhost:7031/api/product
. That should show you the JSON returned, which will be different from the XML. Post that JSON to your original question and we should be able to help further.
My guess is that the JSON is not properly formatted. What does your WebApiConfig.cs class look like?
Update
Yes, there is a better way. First, create an ApiModel (ApiModel is to WebAPI what ViewModel is to MVC):
public class ProductApiModel
{
public int ProductId { get; set; }
public string ProductName { get; set; }
}
Now, return this instead of an entity from your controller:
public class ProductController : ApiController
{
public IEnumerable<ProductApiModel> GetAll()
{
var products = db.Products
.OrderBy(x => x.ProductID)
.Select(x => new ProductApiModel
{
ProductId = x.ProductID,
ProductName = x.ProductName
});
return products;
}
}
If you used AutoMapper, you could make your controller code a bit shorter:
public class ProductController : ApiController
{
public IEnumerable<ProductApiModel> GetAll()
{
var entities = db.Products.OrderBy(x => x.ProductID);
var models = Mapper.Map<ProductApiModel[]>(entities);
return models;
}
}
After do some research, i finaly found (Please Correct Me, if i'm wrong) : JavaScriptSerializer failed to serialize the entire objects tree from relations between the entity and other entities (Product and Catagory).
So .. I made some changes to my code, and the results are as expected
Controller/ProductController.cs :
From :
public class ProductController : ApiController
{
NorthwindEntities db = new NorthwindEntities();
public List<Product> GetAll()
{
return db.Products.ToList<Product>();// ;
}
To :
public class ProductController : ApiController
{
public string GetAll()
{
var product = db.Products.OrderBy(x => x.ProductID).Select(x => new
{
ProductId = x.ProductID,
ProductName = x.ProductName
});
return JsonConvert.SerializeObject(product);
}
View/ViewProduct.aspx :
From :
function getProducts() {
$.getJSON("/api/product",
function (data) {
$.each(data, function (key, val) {
var row = '<tr> <td>' + val.ProductName
+ '</td><td>' + val.ProductID + '</td><tr/>';
$(row).appendTo($('#tblproduct'));
});
});
To :
$.getJSON("/api/product",
function (data) {
var obj = $.parseJSON(data);
$.each(obj, function (key, val) {
var row = '<tr> <td>' + val.ProductId
+ '</td><td>' + val.ProductName + '</td><tr/>';
$(row).appendTo($('#tblproduct'));
});
});
Or... is there a better way than this,
if I still want to pass an entity object instead of a string object (List GetAll ()... instead GetAll string ()....)
Regards,
Andrian
So.. This My Final Working Code
Models :
namespace MyLabs1.Models
{
public class ProductApi
{
[Key]
public Int32 ProductID { get; set; }
public string ProductName { get; set; }
}
}
Controller/ProductController.cs :
public IEnumerable<ProductApi> getall()
{
Mapper.CreateMap<Product, ProductApi>();
var entities = db.Products.OrderBy(x => x.ProductID).ToList();
var models = Mapper.Map<ProductApi[]>(entities);
return models;
}
OR
public List<ProductApi> GetAll()
{
var products = db.Products
.OrderBy(x => x.ProductID)
.Select(x => new ProductApi
{
ProductID = x.ProductID,
ProductName = x.ProductName
}).ToList();
return products;
}
View/ViewProduct.aspx :
function getProducts() { $.getJSON("/api/product", function (data) { $.each(data, function (key, val) { var row = '<tr> <td>' + val.ProductName + '</td><td>' + val.ProductID + '</td><tr/>'; $(row).appendTo($('#tblproduct')); }); }); }
Hope This Will Be Helpful to Others
Regards,
Andrian
来源:https://stackoverflow.com/questions/14183092/asp-net-web-api-crud-operation-in-vs-2010-web-application