Question

I'm trying to consume Northwind OData service in ASP.NET MVC project and using WebGrid controll for vizualizing. I create service reference with Visual Studio 2012 using service URL. Problem is in sorting of WebGrid. When I try to sort it on a navigational field, like CategoryName I get an error: "No property or field 'CategoryName' exists in type 'Product'". I understand the error, but I don't know how to make that work and get a needed portion of data. Any help will be appreciated. Controller:

private ODataNorthwind.NorthwindEntities context = new ODataNorthwind.NorthwindEntities(new Uri("http://services.odata.org/Northwind/Northwind.svc"));
    //
    // GET: /Odata/

    public ActionResult WebGrid(int page = 1, int rowsPerPage = 10, string sort = "ProductID", string sortDir = "ASC")
    {
        var data = GetProducts(page, rowsPerPage, sort, sortDir);
        return View(data);
    }

    // Data for WebGridObj
    private WebGridViewModel GetProducts(int page = 1, int rowsPerPage = 10, string sort = "ProductID", string sortDir = "ASC")
    {
        var query = context.Products.OrderBy(sort + " " + sortDir)
            .Select(p => new
            {
                p.ProductID,
                p.ProductName,
                p.Category.CategoryName,
                p.Supplier.CompanyName,
                p.Supplier.Country
            });

        WebGridViewModel model = new WebGridViewModel
        {
            TotalRows = query.Count(),
            Products = query.Skip((page - 1) * rowsPerPage).Take(rowsPerPage).ToList().Select(p =>
               new HtmlViewModel
               {
                   ProductId = p.ProductID,
                   ProductName = p.ProductName,
                   CategoryName = p.CategoryName,
                   CompanyName = p.CompanyName,
                   Country = p.Country
               })
        };
        return model;
    }

View:

@{
    ViewBag.Title = "WebGrid";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>OData WebGrid</h2>

<div>
@{
    var grid = new WebGrid(null, defaultSort: "ProductId");
    grid.Bind(Model.Products, rowCount: Model.TotalRows, autoSortAndPage: false);
}
@grid.GetHtml(columns: grid.Columns(
    grid.Column("ProductId"),
    grid.Column("ProductName"),
    grid.Column("CategoryName"),
    grid.Column("CompanyName"),
    grid.Column("Country")
    ))
</div>
Was it helpful?

Solution

Passing Category/CategoryName instead of CategoryName as the parameter's sort value when calling GetProducts could solve this problem.

http://services.odata.org/Northwind/Northwind.svc/Products?
     $expand=Category&$orderby=Category/CategoryName
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top