我的数据显示在IE中
[{ “用户ID”:1, “姓”: “Scccce”, “用名字”: “约翰”, “大同”: “0777533303”, “移动”: “07775803803”, “电子邮件”:“john803。 ......
当我希望Javascript触发并创建网格时......
我的控制器代码是:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using Emas.Model;
using Emas.Web.Models.Repositories;
using Emas.Web.Models.FormViewModels;
using Emas.Web.Helpers;
using Emas.Web.Extentions;
using System.Web.Script.Serialization;
namespace Emas.Web.Controllers
{
[Emas.Web.Helpers.AuthorizeHelpers.EMASAuthorize]
public class UserController : Controller
{
private EmasDataContext _db = new EmasDataContext();
private SecurityRepository _securityRepository = new SecurityRepository();
#region Index
public ActionResult Index()
{
//if (!User.IsInRole("Active"))
// return View("NotAuthorised");
if (!User.IsInRole("Admin")) // Only ADMIN users can setup user access and roles
return View("NotAuthorised");
var allUsers = _securityRepository.FindAllUsers();
if (allUsers == null)
return View("NotFound");
return View(allUsers);
}
public JsonResult IndexJSon()
{
//if (!User.IsInRole("Active"))
// return View("NotAuthorised");
//var allUsers = _securityRepository.FindAllUsers();
//return this.Json(allUsers);
var results = from user in _db.aspnet_Users
select new
{
UserId = user.UserId,
Surname = user.Surname,
Forename = user.Forename,
Pax = user.Pax,
Mobile = user.Mobile,
Email = user.Email,
Active = user.Active,
UserName = user.UserName
};
return Json(results);
}
public JsonResult Index2()
{
var results = from user in _db.aspnet_Users
select new
{
UserId = user.UserId,
Surname = user.Surname,
Forename = user.Forename,
Pax = user.Pax,
Mobile = user.Mobile,
Email = user.Email,
Active = user.Active,
UserName = user.UserName
};
return this.Json(results, "text/html");
}
#endregion Index
#region Details
public ActionResult Details(int id)
{
aspnet_User user = _securityRepository.GetUser(id);
if (user == null)
return View("NotFound");
return View(new UserFormViewModel(user, this._securityRepository.FindAllRoles(), this._securityRepository.FindAllUsers()));
}
#endregion Details
#region Delete
[AcceptVerbs(HttpVerbs.Delete)]
public void Delete(int id, string ConfirmButtons)
{
aspnet_User user = _securityRepository.GetUser(id);
this._securityRepository.Delete(user);
this._securityRepository.Save(User.Identity.Name);
}
#endregion Delete
#region Create
// GET:
public ActionResult Create()
{
aspnet_User user = new aspnet_User();
return View(new UserFormViewModel(user, this._securityRepository.FindAllRoles(), this._securityRepository.FindAllUsers()));
}
// POST:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(aspnet_User user, string[] Roles)
{
if (user.UserName != null)
user.LoweredUserName = user.UserName.ToLower();
//TODO dc - hardcoded for demo - fix
user.ApplicationId = new Guid("311566ad-a279-4d0b-a883-89425bdc69e3");
_securityRepository.Add(user);
if (Roles == null)
{
//ModelState.AddModelError("User In Roles", "You must select at least one Role for this user to be in.");
//Code Removed during UAT, being in no Roles implies READ ONLY user
}
else
{
foreach (string role in Roles)
{
aspnet_UsersInRole userInRole = new aspnet_UsersInRole()
{
//RoleId = new Guid(role), GUID removed
UserId = user.UserId
};
user.aspnet_UsersInRoles.Add(userInRole);
}
}
if (!ModelState.IsValid)
return View(new UserFormViewModel(user, this._securityRepository.FindAllRoles(), this._securityRepository.FindAllUsers()));
this._securityRepository.Save(User.Identity.Name);
return RedirectToAction("Index", new { id = user.UserId });
}
#endregion Create
#region Edit
// GET:
public ActionResult Edit(int id)
{
aspnet_User user = _securityRepository.GetUser(id);
if (user == null)
return View("NotFound");
return View(new UserFormViewModel(user, this._securityRepository.FindAllRoles(),this._securityRepository.FindAllUsers()));
}
// POST:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, string[] Roles)
{
aspnet_User user = _securityRepository.GetUser(id);
_securityRepository.DeleteUserInRoles(user);
if (Roles == null)
{
//ModelState.AddModelError("User In Roles", "You must select at least one Role for this user to be in.");
//Code Removed during UAT, being in no Roles implies READ ONLY user
}
else
{
foreach (string role in Roles)
{
aspnet_UsersInRole userInRole = new aspnet_UsersInRole()
{
//RoleId = new Guid(role),
UserId = user.UserId
};
user.aspnet_UsersInRoles.Add(userInRole);
}
}
TryUpdateModel(user);
if (!ModelState.IsValid)
return View(new UserFormViewModel(user, this._securityRepository.FindAllRoles(), this._securityRepository.FindAllUsers()));
this._securityRepository.Save(User.Identity.Name);
return RedirectToAction("Index");
}
public ActionResult ReassignActions(int id)
{
aspnet_User user = _securityRepository.GetUser(id);
if (user == null)
return View("NotFound");
return View(new UserFormViewModel(user, this._securityRepository.FindAllRoles(), this._securityRepository.FindAllUsers()));
}
// POST:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ReassignActions(int id, string[] Roles,Guid UserLoginId)
{
if (!User.IsInRole("Admin")) // If Admin user then block from EDITING
return View("NotAuthorised");
aspnet_User user = _securityRepository.GetUser(id);
//this._db.ReassignUserScheduledActions(user.UserId.ToString(), UserLoginId.ToString());
return View(new UserFormViewModel(user, this._securityRepository.FindAllRoles(), this._securityRepository.FindAllUsers()));
}
#endregion Edit
}
}
我的index2.aspx是:
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="application/json; charset=utf-8" />
<title>My First Grid</title>
<link type="text/css" href="~/Content/jQueryUI/css/jquery-ui-1.8.11.custom.css" rel="stylesheet" />
<link href="~/Content/jquery-1/css/ui.jqgrid.css" rel="stylesheet" type="text/css" />
<style type="text/css">
html, body {
margin: 0;
padding: 0;
font-size: 75%;
}
</style>
<script src="~/Scripts/jquery-1.5.2.js" type="text/javascript"></script>
<script src="~/Content/jquery-1/js/grid.locale-en.js" type="text/javascript"></script>
<script src="~/Content/jquery-1/js/jquery.jqGrid.min.js" type="text/javascript"></script>
</head>
<body>
<table id="list"></table>
<div id="pager"></div>
</body>
</html>
<script type="text/javascript">
$(function() {
alert(33);
$("#list").jqGrid({
url: $("#AbsolutePath").val() + "/User.mvc/Index2",
datatype: 'json',
ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
mtype: 'GET',
colNames: ['UserId', 'Surname', 'Forename', 'Pax', 'Mobile', 'Active', 'Email'],
colModel: [
{ name: 'UserId', index: 'UserId', width: 80, editable: true, editoptions: { size: 10} },
{ name: 'Surname', index: 'Surname', width: 90, editable: true, editoptions: { size: 25} },
{ name: 'Forename', index: 'Forename', width: 60, align: "right", editable: true, editoptions: { size: 10} },
{ name: 'Pax', index: 'Pax', width: 60, align: "right", editable: true, editoptions: { size: 10} },
{ name: 'Mobile', index: 'Mobile', width: 60, align: "right", editable: true, editoptions: { size: 10} },
{ name: 'Active', index: 'Active', width: 55, align: 'center', editable: true, edittype: "checkbox", editoptions: { value: "Yes:No"} },
{ name: 'Email', index: 'Email', width: 100, sortable: false, editable: true, edittype: "textarea", editoptions: { rows: "2", cols: "20"} }
],
pager: '#pager',
rowNum: 10,
rowList: [10, 20, 30],
sortname: 'Surname',
sortorder: 'desc',
viewrecords: true,
caption: 'My first grid'
});
});
</script>
答案 0 :(得分:1)
我不是特别了解ASP.NET,但浏览器会询问您是否要保存该文件,因为该文件的提供方式为HTTP Content-Disposition
header,如下所示:
Content-Disposition: attachment; filename="..."
而不是Content-Disposition: inline;
。
答案 1 :(得分:0)
我注意到了
<%=Html.Action("~/Views/User.mvc/Index2")%>
实际上应该是
<%=Url.Action("~/Views/User.mvc/Index2")%>
Html.Action(...)将动作呈现为内联,而Html.Url(...)返回动作的url。
这可能会改变Html页面的标题信息,因为json结果会产生与查看结果不同的标题,这使浏览器想要下载文件而不是渲染它。
希望这有助于:) text / html
修改强>
如果您问为什么Index2页面要下载 json文件,那是因为标题信息。我可能误解了这个问题。尝试下一步:
return Json(results, "text/html")
这将强制内容类型从“application / octet-stream”变为“text / html”,并告诉浏览器呈现结果,而不是尝试下载。
再次编辑:
现在我理解真正的问题。
你没有得到你期望的HTML的原因是因为你正在返回一个Json结果。 Json结果告诉控制器将对象序列化为json并将其打印到响应中。在任何情况下, NOT 都会返回视图。
要呈现视图,必须返回从ViewResultBase派生的对象。默认的Controller类有很多View(...)方法可以为你处理。
您的方案中需要两个操作,第一个操作将呈现视图:
public ActionResult Index()
{
// This will find a view with the name of the action (in this case, "Index")
return View();
}
在Index.aspx页面中,您需要使用
设置jqgridurl:'<%= Url.Action("IndexDataJson") %>',
您需要在控制器上执行另一个操作才能返回jqgrid行:
public ActionResult IndexDataJson(string sidx, string sord, int page, int rows)
{
var results = from user in _db.aspnet_Users
select new
{
// Your properties here
};
var usersOnPage = results.Skip((page-1) * rows).Take(rows).ToList();
// This is the correct format for the jqgrid result
var model = new
{
total = results.Count,
page = page,
records = usersOnPage.Count,
rows = usersOnPage
}
// Ignore the "text/html" mentioned earlier, as you probably wont need it
return Json(model, JsonRequestBehavior.AllowGet);
}
请记住,如果jqgrid没有加载任何数据,您可能需要修改ajaxReader ...
希望这完全回答了你的问题。 :)
有关更多信息,请参阅Phil Haack关于此主题的博文:
http://haacked.com/archive/2009/04/14/using-jquery-grid-with-asp.net-mvc.aspx
答案 2 :(得分:0)
在我看来,服务器正在正确响应。这是浏览器或插件没有表现。我已经看到浏览器尝试将JSON结果作为文件下载的时间是异步发送请求的时间。我知道这是一个AJAX插件,但是用fiddler或firebug确认请求是用XHR头发送的。您还可以检查响应标头以查看Content-Type是什么。我从那里开始,检查请求和任何异常的响应,因为你的代码看起来正确。
在行动方面,我从未在"text/Html
来电中加入return Json()
。我总是用这个......
return Json(new {message = "some message goes here"} , JsonRequestBehavior.AllowGet);
此代码的响应标头如下所示..
HTTP/1.1 200 OK
Cache-Control: private, s-maxage=0
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/7.5
X-AspNetMvc-Version: 3.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Wed, 13 Apr 2011 04:21:47 GMT
Content-Length: 29
答案 3 :(得分:0)
再看一下...... index2.aspx是如何渲染的?你永远不会返回那个视图。
该视图需要使用return View("index2")
呈现。然后,jqGrid插件将进行额外的AJAX调用以检索Json数据。从它的外观来看,你永远不会真正加载那个javascript。
这是我的建议。
public ActionResult Index2()
{
return View('Index2');
}
public JsonResult Index2Data() //RENAME TO SOMETHING BETTER
{
var results = from user in _db.aspnet_Users
select new
{
UserId = user.UserId,
Surname = user.Surname,
Forename = user.Forename,
Pax = user.Pax,
Mobile = user.Mobile,
Email = user.Email,
Active = user.Active,
UserName = user.UserName
};
return Json(results, JsonRequestBehavior.AllowGet);
}
然后在您的浏览器中,如果您点击http://site/User/Index2,您将首先返回将加载javascript的aspx页面。随着javascript加载,jqGrid插件应该触发另一个调用来检索Json数据。
请务必使用“index2data”或您调用的任何内容更新您的jqGrid网址。网格需要知道从哪里获取数据。