微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript-使用dojo的jsonRest复杂结构

我正在开发基于dojo框架的Web应用程序.

我决定使用dojox.data.JsonRestStore与服务器进行通信.

例如,我在Json中具有订单(电子商务)的这种表示形式:

{
id: int,
name: str,
date: str,
items: [
    {
        id: int,
        name: str,
        pcs: int,
        price: int,
        total: int

    }, ...
]
}

订单具有一些基本属性(id,名称,日期),并且还包含订购商品的数组.

我不确定这是否是好的(REST)设计,并且我想知道订购的商品是否应该在单独的资源中(因此也应该在单独的jsonRestStore中).

我想在dojo Form中显示Orders的基本属性,而在dojo Datagrid中显示Ordered的项目时,可能对当前的对象模型有麻烦.

所以我的问题是,我当前的方法是否可行-以创建REST客户端应用程序的方式?另外,在dojo中使用datagrid实现示例表单的正确方法是什么?

解决方法:

虽然您的设计是RESTful的,而REST体系结构中没有任何要求,但我认为大多数人都同意将资源分开是最好的方法.如果您检出Restful Web Services,他们会将其描述为面向资源的体系结构.

我已经制定了一个示例,将订单和项目保留在单独的JsonRestStores中,并允许您通过Dojo表单显示Order对象,并通过Dojo DataGrid显示订单的项目.我认为代码很简单,我还在代码添加了一些注释,以尝试清除问题.

我创建了一个简单的ASP.NET MVC 3后端,以为该示例提供一些虚拟数据.我也发布了该代码,尽管您实际上只对代码的“查看”部分感兴趣,但后端代码也可以帮助您弄清或更改您拥有的任何后端代码.

视图:

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
   <title>JsonRestStore Datagrid Example</title>

<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/dojo/1.6.1/dojo/resources/dojo.css"/>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/dojo/1.6.1/dijit/themes/tundra/tundra.css"/>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/dojo/1.6.1/dojox/grid/resources/Grid.css"/>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/dojo/1.6.1/dojox/grid/resources/tundraGrid.css"/>

<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/dojo/1.6.1/dojo/dojo.xd.js' djConfig="parSEOnLoad:true"></script>

<script type="text/javascript">

    dojo.require("dojox.data.JsonRestStore");
    dojo.require("dojox.grid.DataGrid");
    dojo.require("dijit.form.DateTextBox");
    dojo.require("dojox.grid.cells.dijit");
    dojo.require("dojo.date.locale");
    var item_structure = null;

    dojo.ready(function () {
        setItemTableStructure();
        //retrieve a single order
        //expects json to look like
        // {"Id":2,"Name":"Order Name 2","Date":"\/Date(1321135185260)\/","Items":{"Ref":"/Order/2/Items"}}
        order_store = new dojox.data.JsonRestStore({ target: "/Order/2", idAttribute: "Id" });

        order_store.fetch({
            onComplete: function (item) {
                //this method is called after an item is fetched into the store
                //item here is the order json object
                var orderId = new dijit.form.TextBox({ value: order_store.getValue(item, 'Id') }, 'orderId');
                var orderName = new dijit.form.TextBox({ value: order_store.getValue(item, 'Name') }, 'orderName');
                var orderDate = new dijit.form.DateTextBox({ value: parseJsonDate(order_store.getValue(item, 'Date')) }, 'orderDate');
                var items = order_store.getValue(item, 'Items').Ref;

                //make a call to retrieve the items that are contained within a particular order
                //expects a json object that looks like
                //[{"Ref":"/Item/1"},{"Ref":"/Item/2"},{"Ref":"/Item/3"},{"Ref":"/Item/4"},{"Ref":"/Item/5"}]
                var xhrArgs = {
                    url: items,
                    handleAs: "json",
                    load: loadOrder, //main method
                    error: function (error) {
                        console.log(error);
                    }
                }
                var deferred = dojo.xhrGet(xhrArgs);
            }
        });
    });

    //This is the main method
    function loadOrder(data) {
        var itemIds = "";
        dojo.forEach(data, function(item, i){
            itemIds += item.Ref.charat(item.Ref.length-1);
            itemIds += ",";
        });
        itemIds = itemIds.substring(0, itemIds.length-1);

        //build the backend to accept a comma seperated list of item ids
        //like    /Item/1,2,3
        item_store = new dojox.data.JsonRestStore({target:"/Item/" + itemIds, idAttribute:"Id"});
        items = new dojox.grid.DataGrid({
            name: "items",
            formatter: function(date) {
                        if (date) return dojo.date.locale.format(parseJsonDate(date), {
                            selector: "Date"
                        })
                    },
            structure: item_structure,
            store: item_store
        }, dojo.byId('orderItems'));

        items.startup();
    }

    function setItemTableStructure() {
        item_structure = [
        { 
          field: 'Id'
        },
        {
          field: 'Name'
        },
        {
          field: 'Price'
        },
        {
            field: 'Date',
            type: dojox.grid.cells.DateTextBox,
            widgetProps: {
                selector: "Date"
            },
            formatter: function(v) {
                if (v) return dojo.date.locale.format(parseJsonDate(v), {
                    selector: 'Date'
                })
            }
        }];
    }

    function parseJsonDate(jsonDate) {
        var offset = new Date().getTimezoneOffset() * 60000;
        var parts = /\/Date\((-?\d+)([+-]\d{2})?(\d{2})?.*/.exec(jsonDate);

        if (parts[2] == undefined)
          parts[2] = 0;

        if (parts[3] == undefined)
          parts[3] = 0;

        return new Date(+parts[1] + offset + parts[2]*3600000 + parts[3]*60000);
    }
  </script>
  </head>
  <body>
    <h1>Json Rest Store with DataGrid Example</h1><br />

    <form style='margin: 10px' action='post'>
    <h2>Order</h2>
    <input id='orderId' />
    <input id='orderName' />
    <input id='orderDate' />
    </form>
    <h2>Items</h2>
    <div id='orderItems'></div>
    </body>
 </html>

楷模:

using System;

namespace OrdersRestService.Models
{
    public class Item
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public double Price { get; set; }
        public DateTime Date { get; set; }
    }
}

public class Order
{
    public int Id { get; set; }
    public string Name { get; set; }
    public DateTime Date { get; set; }
    public Reference Items { get; set; }
}

public class Reference
{
    public string Ref { get; set; }
}

控制器:

namespace OrdersRestService.Controllers
{
    public class OrderController : Controller
    {
        public ActionResult Index(string id)
        {
            Order order = new Order
                              {
                                  Id = Convert.ToInt32(id),
                                  Name = "Order Name " + id,
                                  Date = DateTime.Now,
                                  Items = new Reference
                                                {
                                                    Ref = "/Order/" + id + "/Items"
                                                }
                              };

            return Json(order, JsonRequestBehavior.AllowGet);
        }

        public ActionResult Items()
        {
            List<Reference> items = new List<Reference>();

            for (int i = 1; i <= 5; i++)
            {
                Reference r = new Reference();
                r.Ref = "/Item/" + i;
                items.Add(r);
            }

            return Json(items, JsonRequestBehavior.AllowGet);
        }
    }

    public class ItemController : Controller
    {
        public ActionResult Index(string id)
        {
            List<Item> items = new List<Item>();
            foreach (string itemid in id.Split(','))
            {
                Item item = new Item 
                                  {
                                      Id = Convert.ToInt32(itemid),
                                      Name = "Item Name " + itemid,
                                      Date = DateTime.Now,
                                  };
                items.Add(item);
            }

            return Json(items, JsonRequestBehavior.AllowGet);
        }
    }

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
    }
}

Global.aspx.cs

public class MvcApplication : System.Web.HttpApplication
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
    }

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "DefaultWithAction", // Route name
            "{controller}/{id}/{action}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );
    }

    protected void Application_Start()
    {
        AreaRegistration.RegisterallAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐