0
我遇到了jQuery模板有趣的問題。我希望能夠通過JSON(我已經工作)獲得動態模板,然後通過JSON匹配該模板,這是我的問題所在。jQuery模板與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的返回的數據,我得到的東西看起來像這樣(我刪除的用戶名,這是在左邊空白處):
從JSON請求回來的數據與「硬編碼」數組(arr)100%相同。我在結果上使用了Beyond Compare,它們完全相同。
對於徹底:這是返回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請求中返回?