odata mvc wcf调用方法

来源:互联网 发布:网络英语课程哪个好 编辑:程序博客网 时间:2024/06/17 12:35

1.add service reference http://services.odata.org/Northwind/Northwind.svc

2.create a product.class inherit "proxy".Product

3.

   public ActionResult Index()        {            ViewBag.Message = "Welcome to ASP.NET MVC!";            var context = new NorthwindEntities(new Uri("http://services.odata.org/Northwind/Northwind.svc/"));            var products = from product in context.Products                           select product;            ViewData["ProductList"] = products.ToList();            return View();        }


4.

  <%= Html.Telerik().StyleSheetRegistrar()        .DefaultGroup(group => group.Add("telerik.common.css")                                    .Add("telerik.vista.css"))    %>    <h2><%: ViewBag.Message %></h2>    <p>        To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc</a>.    </p>    <% Html.Telerik().TreeView()       .Name("TreeView")       .Items(items =>       {           foreach (Product pro in (List<Product>)ViewData["ProductList"])           {               items.Add().Text(pro.ProductName);           }       })       .ClientEvents(events => events.OnLoad("onLoad"))       .Render();%>

Display


success!


原文部分内容:

I created this quick demo on consuming a WCF Data Service to get my feet wet with OData feeds. I thought it might be a good quick start guide for anyone getting started. Enjoy!


Referencing the Service

After creating the MVC 3 Application our first step is to add the service reference to leverage the proxy class generated for us.

addServiceRef

Now that we have our proxy class let’s go ahead and add a strongly-typed partial view in the Home folder for the products.

addView

Once we have a list view to show the products, we can add our call to get the view into the main page using the helper Html.RenderPartial.

<div>
    <h1>Products</h1>
    <hr/>
    <div>
        @{Html.RenderPartial("ProductList", new List<MvcApplication5.NorthwindService.Product>());}
    </div>
</div>

On the controller side, we will access the products from the OData feed and return them to the view. Since the OData feed is a RESTful service we could just add /Products to the service url and retrieve them:

http://services.odata.org/Northwind/Northwind.svc/Products

But since I have the generated class available I can just use it’s context and LINQ to get the products:

01public PartialViewResult Products(intcategoryId)
02{
03    var context =newNorthwindEntities(newUri("http://services.odata.org/Northwind/Northwind.svc/"));
04 
05    var products = from productincontext.Products
06                    where product.CategoryID == categoryId
07                    select product;
08 
09    returnPartialView("ProductList", products.ToList());
10}

The last thing we need to do is show a select list of categories to sort by and wire it up to change the list using some jQuery binding.

Our page now looks like this:

    <scriptsrc="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")"type="text/javascript"></script>
    <scripttype="text/javascript">
        $(document).ready(function () {
            $("#category").change(function () {
                loadView($(this).val());
            });
            loadView("1");
        });
        function loadView(cat) {
            $("#results").load('@Url.Action("Products", "Home")', { 'categoryId': cat });
        }
    </script>
<nav>
</nav>
 
<div>
    <h1>Products</h1>
    <div>
        <div>Category:</div>
        @Html.DropDownList("category",
            MvcApplication5.Controllers.HomeController.Categories().Select(
                c => new SelectListItem {
                    Text = c.CategoryName,
                    Value = c.CategoryID.ToString()
                }))
    </div>
    <hr/>
    <div>
        @{Html.RenderPartial("ProductList", new List<MvcApplication5.NorthwindService.Product>());}
    </div>
</div>

And in our controller we add the method to get our categories:

1static publicList<Category> Categories()
2 {
3     var context =newNorthwindEntities(newUri("http://services.odata.org/Northwind/Northwind.svc/"));
4     returncontext.Categories.ToList();
5 }

Run this and we see our results based on the category chosen:

results


Output Caching

Okay, so we have our products and can change them by category. Let’s take advantage ofOutput Caching since the products will not change much (except of course the units in stock). Output Caching is easy to accomplish by adding an attribute to the controller action. If you want you can also useAction Filtering to handle all controllers and actions, providing a great level of caching granularity. Back to our products, just add the OutputCache attribute to the action along with some parameters you can play with to see it working.

1[OutputCache(Duration=30, VaryByParam="categoryId")]
2        publicPartialViewResult Products(intcategoryId) {

Let’s look at this in action in Firebug to really see what’s happening. The first three calls show the first time I select the category. I then select each category again and we can see the difference in response time:

firebug

And there we have it. Consuming a WCF Data Service public OData feed and caching the output by parameter.

原创粉丝点击