jquery模板,带有对模板和数据的JSON调用

时间:2011-06-24 14:42:06

标签: jquery asp.net-mvc jquery-templates

我遇到了jQuery模板的一个有趣问题。我希望能够通过JSON(我已经工作)获得动态模板,然后通过JSON匹配该模板,这就是我的问题所在。

以下是模板内容的内容:

$.getJSON('@Url.Action("GenerateAdminTemplate", "Home", new { area = "" })', function (data) {
    if (data.Success) {
        adminListTemplate = data.Result;
        $("#adminListHeader").html(data.Header);
        $.getJSON('@Url.Action("GenerateAdminSheet", "Home", new {area = ""})', function (dataz) {
            if (dataz.Success) {
                $("#templateListing").text(data.Result);
                $("#markupBeforeTemplateListing").text(dataz.Result);
                var myTemplate = $.template(null, data.Result);

                //var arr = [
                //  { Name: "User1", Administrator: "yes", Supervisor: "no", User: "yes" },
                //  { Name: "User2", Administrator: "yes", Supervisor: "no", User: "no" }
                //];

                var arr = dataz.Result;

                $.tmpl(myTemplate, arr).appendTo("#adminListBody");
            } else {

            }
        });
    } else {
    }
});

模板本身回来并成功。当我取消注释硬编码数组(arr)并使用它而不是返回的值时,表格显示正如我所期望的那样。但是,当我使用JSON返回的数据时,我得到的内容看起来像这样(我删除了用户名,左边是空白区域):

jQueryTemplateResult

从JSON请求返回的数据与“硬编码”数组(arr)完全相同。我在结果上使用了Beyond Compare,它们是100%完全相同的。

彻底性:这是返回JSon数据的代码:

public JsonResult GenerateAdminSheet()
{
    bool success = false;
    String errorMessage = String.Empty;
    StringBuilder result = new StringBuilder();


    try
    {
        List<String> listOfUsersAndRoles = new List<String>();

        using (DataUtilityEntities data = new DataUtilityEntities(ConfigurationManager.ConnectionStrings["DataUtilityConnection"].ConnectionString))
        {
            List<User> users = data.Users.ToList();

            foreach (User u in users)
            {
                List<Role> rolesUserBelongsTo = data.UserInRoles.Where(o => o.UserId == u.UserId).Select(p => p.Role).ToList();

                CustomDictionary allRoles = new CustomDictionary();

                //add the username as the first entry in the dictionary
                allRoles.Add("Name", u.Username);

                List<Role> allRolesList = data.Roles.ToList();

                foreach (Role r in allRolesList)
                {
                    allRoles.Add(String.Format("{0}", r.Name), rolesUserBelongsTo.Exists(p => p.Name == r.Name) ? "yes" : "no");
                }

                listOfUsersAndRoles.Add(allRoles.ToString());
            }

        }

        //We have the list of the objects to pass back, now we just need to format them so they will work properly
        result.Append("[");
        foreach (String item in listOfUsersAndRoles)
        {
            result.Append(item);
            if (listOfUsersAndRoles.Last() != item)
                result.Append(", ");
        }
        result.Append("]");

        success = true;
    }
    catch (Exception e)
    {
        success = false;
        errorMessage = String.Format("@There was an error: {0}{1}", e.Message, e.InnerException == null ? String.Empty : String.Format("@({0})", e.InnerException.Message));
    }

    return Json(new { Success = success, ErrorMessage = errorMessage, Result = result.ToString() }, JsonRequestBehavior.AllowGet);

CustomDictionary只是.ToString()的重写:

public override string ToString()
{
    StringBuilder result = new StringBuilder();
    result.Append("{ ");

    foreach (var pair in this)
    {
        result.Append(String.Format("{0}: \"{1}\"{2}", pair.Key, pair.Value, this.Last().Key == pair.Key ? String.Empty : ", "));
    }

    result.Append(" }");
    return result.ToString();
}

当结果从JSon请求返回时,是否有遗漏的东西?

1 个答案:

答案 0 :(得分:0)

在同事的帮助下弄清楚问题。 事实证明,模板不会将字符串值作为对象,因此您需要将其解析为JSON对象:

var arr = dataz.Result.toString();

var obj = $.parseJSON(arr);

但是,有一点需要注意,我这样做的方式略有不正确,$.parseJSON方法会因“格式错误”的json而抛出异常。

我上面的内容:

[{Name: "user", Administrator: "yes" ... }, {Name: "user2", ...}] 

无效,需要:

[{"Name": "user", "Administrator": "yes" ...}, {"Name": "user2", ...}]