ASP.NET Web Api CRUD operation in VS 2010 web application

早过忘川 提交于 2019-12-02 09:00:14

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;
    }
}
ANDRI N

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!