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

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-02 15:11:49

问题


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 ?


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/14183092/asp-net-web-api-crud-operation-in-vs-2010-web-application

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