JSON 将原始序列化数据返回到浏览器页面,而不是网格和格式化 HTML

发布于 2024-10-31 18:40:34 字数 10754 浏览 1 评论 0原文

我的数据在 IE 中显示为

[{"UserId":1,"Surname":"Scccce","Forename":"John","Pax":"0777533303","Mobile":"07775803803","Email": “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>

My Data appears in IE like

[{"UserId":1,"Surname":"Scccce","Forename":"John","Pax":"0777533303","Mobile":"07775803803","Email":"john803.......

When I want the Javascript to fire and create a grid...

My Controller Code is:

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                               
    }
}

My index2.aspx is:

<%@ 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>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

耳钉梦 2024-11-07 18:40:34

我不太了解 ASP.NET,但浏览器会询问您是否要保存文件,因为该文件是通过 HTTP Content-Disposition header 像这样:

Content-Disposition: attachment; filename="..."

而不是 Content-Disposition: inline;

I don't know specifically about ASP.NET, but the browser asks if you want to save the file because the file is served with a HTTP Content-Disposition header like this:

Content-Disposition: attachment; filename="..."

rather than Content-Disposition: inline;.

浪推晚风 2024-11-07 18:40:34

在我看来,服务器响应正确。这是浏览器或插件不工作的原因。我曾多次看到浏览器在未异步发送请求时尝试将 JSON 结果下载为文件。我知道这是一个 AJAX 插件,但使用 fiddler 或 firebug 确认请求是使用 XHR 标头发送的。您还可以检查响应标头以了解 Content-Type 是什么。我将从这里开始,检查请求和响应是否有任何异常,因为您的代码看起来是正确的。

在操作方面,我从来没有必要在 return Json() 调用中包含 "text/Html。我总是使用这个...

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

It looks to me like the server is responding correctly. It's the browser or the plugin that isn't behaving. Times I've seen the browser attempt to download a JSON result as a file is when the request was not sent asynchronously. I know this is an AJAX plugin, but confirm with fiddler or firebug that the request is sent with an XHR header. You can also check the response header to see what the Content-Type is. I'd start there, examine the request and response for any abnormalities because your code looks right.

On the action side I've never had to include "text/Html in my return Json() calls. I always use this...

return Json(new {message = "some message goes here"} , JsonRequestBehavior.AllowGet);

The response header from this code looks like this..

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
瀟灑尐姊 2024-11-07 18:40:34

再看一遍...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 您将首先返回 aspx 页面将加载 JavaScript。当 javascript 加载时,jqGrid 插件应该触发另一个调用来检索 Json 数据。

请务必使用“index2data”或任何您所称的名称更新您的 jqGrid url。网格需要知道从哪里获取数据。

After a second look... How is index2.aspx getting rendered? You never return that View.

That View needs to have been rendered with return View("index2") The jqGrid plugin will then make an additional AJAX call to retrieve the Json data. From the looks of it, you're never actually loading that javascript.

Here's what I would suggest.

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);

        }

Then in your browser if you hit http://site/User/Index2 you'll first return the aspx page that will load the javascript. As the javascript loads the jqGrid plugin should fire off another call to retrieve the Json data.

Be sure to update your jqGrid url with "index2data" or whatever you call it. The grid needs to know where to get the data from.

傲影 2024-11-07 18:40:34

我注意到

<%=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 并将其打印到响应中。在任何情况下,它都不返回视图。

要呈现视图,您必须返回从 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 页面内,您将需要设置 jqgrid

url:'<%= 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

I notice that

<%=Html.Action("~/Views/User.mvc/Index2")%>

should in fact be

<%=Url.Action("~/Views/User.mvc/Index2")%>

Html.Action(...) renders the action inline, whereas Html.Url(...) returns the url of the action.

This is probably changing the header information of the Html page, as json results produce different headers than view results, which makes the browser want to download the file rather than render it.

Hope this helps :) text/html

edit:

If you are asking why the Index2 page wants you to download the json file, it's because of the header information. I may have misunderstood the question to begin with. Try the folling:

return Json(results, "text/html")

This will force the content type from "application/octet-stream" to "text/html", and will tell the browser to render the result, rather than try to download it.

edit, again:

Now I'm understanding the real question.

The reason you're not getting the HTML you're expecting is because you're returning a Json result. A Json result tells the controller to serialize an object to json and print it to the response. It does NOT return a view, under any circumstances.

To render a view, you must return an object derived from ViewResultBase. The default Controller class has many View(...) methods that can handle this for you.

You will need two actions in your scenario, the first action will render the view:

public ActionResult Index()
{
    // This will find a view with the name of the action (in this case, "Index")
    return View();
}

Inside your Index.aspx page, you will need to setup jqgrid with

url:'<%= Url.Action("IndexDataJson") %>',

And you'll need another action on your controller to return the jqgrid rows:

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);
}

Keep in mind that you may need to modify the ajaxReader for the jqgrid if it doesn't load any data...

Hopefully this fully answers your question. :)

For more information, pleas refer to Phil Haack's blog post about this topic:

http://haacked.com/archive/2009/04/14/using-jquery-grid-with-asp.net-mvc.aspx

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文