与jQuery的ASP.NET MVC - 呼吁支持AJAX的Web服务 [英] jquery with ASP.NET MVC - calling ajax enabled web service

查看:154
本文介绍了与jQuery的ASP.NET MVC - 呼吁支持AJAX的Web服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个有点延续了<一的href="http://stackoverflow.com/questions/2830335/jqgrid-edit-function-never-getting-called">$p$pvious的问题。

现在我试图拨打电话,而我已在ASP.NET MVC应用程序中定义的启用AJAX的Web服务(即 MovieService.svc )。但是服务永远不会被称为在我的 getMovies JavaScript函数。

这同样调用AJAX的Web服务技术的工作原理确定,如果我尝试在非ASP.NET MVC应用程序,所以它使我不知道,如果可能的ASP MVC路由干扰的东西莫名其妙地当它试图使AJAX Web服务调用。

你有任何想法,为什么我的web服务是没有得到叫什么名字?低于code。

 &LT;脚本SRC =&LT;%= ResolveClientUrl(〜/脚本/ jQuery的-1.4.2.min.js)%&gt;中类型=文/ JavaScript的&GT;&LT; / SCRIPT&GT;

    &所述;脚本的src =&其中;%= ResolveClientUrl(〜/脚本/ grid.locale-en.js)%&gt;中类型=文/ JavaScript的&GT;&LT; / SCRIPT&GT;

    &LT;脚本SRC =&LT;%= ResolveClientUrl(〜/脚本/ jQuery的-UI-1.8.1.custom.min.js)%&gt;中
        类型=文/ JavaScript的&GT;&LT; / SCRIPT&GT;

    &所述;脚本的src =&其中;%= ResolveClientUrl(〜/脚本/ jquery.jqGrid.min.js)%&gt;中类型=文/ JavaScript的&GT;&LT; / SCRIPT&GT;

    &LT;脚本类型=文/ JavaScript的&GT;
        VAR lastsel2;

        功能successFunction(jsondata){
            调试器
            变种thegrid = jQuery的(#Editgrid的);
            对于(VAR I = 0; I&LT; jsondata.d.length;我++){
                thegrid.addRowData第(i + 1,jsondata.d [I]);
            }
        }

        功能getMovies(){
            调试器
            // *****的MovieService#GetMovies方法永远不会被调用
            $阿贾克斯({
                网址:MovieService.svc / GetMovies',
                数据:{},//为空输入数据使用{},
                数据类型:JSON,
                键入:GET,
                的contentType:应用/ JSON的;字符集= UTF-8,
                成功:successFunction
            });
        }

        jQuery的(文件)。就绪(函数(){
            jQuery的(#Editgrid的)。jqGrid的({
                数据类型:getMovies,
                colNames:['身份证','电影名称,导演,发布日期,IMDB评分,块,IMAGEURL'],
                colModel:
                  {名字:'身份证',索引:'身份证',宽度:55,排序:假的,隐藏的:真正的,可编辑的:假的,editoptions:{只读:真正的,尺寸:10}},
                  {名称:电影名称,索引:名称,宽度:250,可编辑:真正的,editoptions:{尺寸:10}},
                  {名称:'导演',索引:'导演',宽度:250,对齐:权,可编辑:真正的,editoptions:{尺寸:10}},
                  {名称:发布日期,索引:RELEASEDATE',宽度:100,对齐:权,可编辑:真正的,editoptions:{尺寸:10}},
                  {名字:IMDB评分,索引:IMDBUserRating',宽度:100,对齐:权,可编辑:真正的,editoptions:{尺寸:10}},
                  {名称:'剧情',索引:'情节',宽度:150,隐藏的:假的,可编辑:真正的,editoptions:{尺寸:30}},
                  {名字:IMAGEURL,索引:IMAGEURL',宽度:55,隐蔽性:真实,可编辑:假的,editoptions:{只读:真正的,尺寸:10}}
                ]
                寻呼机:jQuery的('#寻呼机),
                的rowNum:5,
                rowList:[5,10,20],
                sortname:'身份证',
                排序顺序:递减,
                高度:100%,
                宽度:'100%',
                viewrecords:真正的,
                imgpath:'/内容/ jqGridCss /雷蒙德/图像,
                标题:从2008年电影,
                editurl:/首页/ EditMovieData /',
                标题:电影榜
            });

            $(#bedata)。点击(函数(){
                变种克= jQuery的(#Editgrid的)jqGrid的('getGridParam','selrow')。
                如果(GR!= NULL)
                    jQuery的(#Editgrid的)jqGrid的('editGridRow',GR,{高度:280,reloadAfterSubmit:假});。
                其他
                    警报(嘿白痴,请选择行);
            });

        });

    &LT; / SCRIPT&GT;

    &LT; H2&GT;
        &LT;%= Html.En code(计算机[信息])%&GT;&LT; / H&GT;
    &其中p为H.;
        要了解更多关于ASP.NET MVC访问&LT; A HREF =htt​​p://asp.net/mvc称号=ASP.NET MVC网站&GT;
            http://asp.net/mvc</a> ;.
    &所述; / P&GT;
    &LT;表ID =Editgrid的&GT;
    &LT; /表&gt;
    &LT; D​​IV ID =寻呼机的风格=文本对齐:中心;&GT;
    &LT; / DIV&GT;
    &LT;输入类型=按钮ID =bedata值=编辑选择/&GT;
 

下面是我的RegisterRoutes code:

 公共静态无效的RegisterRoutes(RouteCollection路由)
{
    routes.IgnoreRoute({}资源个.axd / {* PATHINFO});
    routes.IgnoreRoute(* MovieService.svc *);

    routes.MapRoute(
        默认,//路线名称
        {控制器} / {行动} / {ID},// URL与参数
        新{控制器=主页,行动=索引,ID =} //参数的默认值
    );
}
 

下面就是我的MovieService类是这样的:

 命名空间jQueryMVC
{
    [的ServiceContract(命名空间=)]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)
    公共类MovieService
    {
        //添加[WebGet]属性来使用HTTP GET
        [OperationContract的]
        [WebGet(ResponseFormat = WebMessageFormat.Json)
        公众的IList&LT;电影&GT; GetMovies()
        {
            返回Persistence.GetMovies();
        }

    }
}
 

解决方案

您的主要问题是,你使用不是在 AJAX 通话绝对URL。在 web.config中输入错误也可以使问题。此外,您使用数据类型:getMovies 而不是数据类型:JSON POSTDATA:yourData 。与数据类型的功能存在(见的 http://www.trirand.com/jqgridwiki/doku.php?id=wiki:retrieving_data#function ),但由于jqGrid的3.6.5你有内部更直接的方式 jsonReader 来读取数据从Web服务器返回。

更新: 在我看来,这描述的编辑功能,我将在后面作解释这里只是如何获取JSON数据和jqGrid的内部填充有。

首先jqGrid的都可以从服务器请求本身的JSON数据。所以我们并不需要做一个单独的 jQuery.ajax 通话。你只需要定义一个指向该服务器的URL,并定义了一些额外的 jQuery.ajax 参数,你preFER。 你不会在你的问题发布电影类的定义。所以,我把它定义自己喜欢以下

 公共类电影{
    公众诠释编号{获得;组; }
    公共字符串名称{;组; }
    公共字符串董事{获得;组; }
    公共字符串RELEASEDATE {获得;组; }
    公共字符串IMDBUserRating {获得;组; }
    公共字符串情节{获得;组; }
    公共字符串IMAGEURL {获得;组; }
}
 

您应该一句话,说微软连载 DATATIME 键入而不是作为一个可读的日期字符串,但作为一个字符串 /日(utcDate)/ ,其中 utcDate 是这个数 (见<一href="http://stackoverflow.com/questions/2794633/jquery-param-doesnt-serialize-javascript-date-objects/2794836#2794836">http://stackoverflow.com/questions/2794633/jquery-param-doesnt-serialize-javascript-date-objects/2794836#2794836).要在一开始我定义 RELEASEDATE 作为字符串进行较少的问题。

方法的IList&LT;电影&GT; GetMovies()返回JSON数据,如电影的对象的数组。所以jqGrid的以HTTP GET 请求的响应接收来自 MovieService.svc / GetMovies URL如下面的数据:

  [{ID:1,名称:ET,导演:史蒂芬·斯皮尔伯格,...},{...} ... ]
 

我可以说,这是不是数据,这是等待jqGrid的(用的 http://www.trirand.com/jqgridwiki/doku.php?id=wiki:retrieving_data#json_data )。为了能够将数据jqGrid的内部,我们必须定义一个 jsonReader 。所以我们下面的

 的jQuery(#Editgrid的)。jqGrid的({
    网址:'&LT;%= Url.Content(〜/ MovieService.svc / GetMovies)%&GT;',
    数据类型:JSON,
    ajaxGridOptions:{的contentType:应用/ JSON的},
    jsonReader:{repeatitems:假的,ID:ID,根:函数(OBJ){返回OBJ; }},
    headertitles:真正的,
    排序:真正的,
    colNames:电影名称,导演,发布日期,
               IMDB评分,块,IMAGEURL'],
    colModel:
        {名称:名称,宽度:250},
        {名字:'导演',宽度:250,对齐:权},
        {名字:RELEASEDATE',宽度:100,对齐:权},
        {名字:IMDBUserRating',宽度:100,对齐:权},
        {名称:'剧情',宽度:150},
        {名字:IMAGEURL',宽度:55,隐藏的:真正}
    ]
    寻呼机:jQuery的('#寻呼机),
    pginput:假的,
    的rowNum:0,
    高度:100%,
    viewrecords:真正的,
    rownumbers:真正的,
    标题:从2008年电影
})jqGrid的('navGrid','#pager',{加:假的,编辑:假的,德尔:假的,搜索:虚假});
 

备注:我从这个例子中删除任何排序参数,因为在案件的JSON数据请求,排序参数将只发送给服务器(一些额外的参数追加服务器URL)和服务器必须还给排序的数据。欲了解更多信息,请参阅 prmNames 参数说明上的 http://www.trirand.com/jqgridwiki/doku.php?id=wiki:options SOPT 参数的描述< A HREF =htt​​p://www.trirand.com/jqgridwiki/doku.php?id=wiki:singe_searching相对=nofollow> http://www.trirand.com/jqgridwiki/doku.php?id=维基:singe_searching

对于的数据类型:'json的我们定义数据类型:JSON参数 jQuery.ajax (不要混淆数据类型参数内的情况下)。所有字段 colModel 我们定义的内部名称确切同里我们JSON对象的字段名。一些额外的参数 viewrecords rownumbers 排序 headertitles 不在这个例子很重要,我选用那里,因为1)我喜欢那里,2)我设置的rowNum:0 以便能够选择 rownumbers:真正的工作正确的,而不是给我们的负面行号开始-5如果的rowNum:5 就像你原来的例子。

使用 ajaxGridOptions:{的contentType:应用/ JSON的} 我们定义这将是额外的参数的直接转发到 jQuery.ajax

这个例子中最复杂的部分是

  jsonReader:{repeatitems:假的,ID:ID,根:函数(OBJ){返回OBJ; }}
 

它定义了所有行的ID的名称为ID(请参阅​​类电影的定义)。 repeatitems:假说,我们希望通过字段名称标识每个数据字段( colModel 中定义),而不是每个位置的默认定义。的定义是有些奇怪,但是它定义了如何找到JSON数据内的 。 JSON数据默认格式是如下

  {
  总:XXX,
  页面:YYY
  记载:ZZZ,
  行:
    {编号:1,细胞:[cell11,cell12,CELL13]},
    {ID:2,细胞:[CELL21,cell22,cell23]},
      ...
  ]
}
 

和行的根被定义为根:行。因此,如果分配给变量 RES JSON数据,根可返回 res.rows 。为了让jqGrid的读取我们的数据,我们定义 jsonReader.root 作为一个功能(此功能存在,因为jqGrid的3.6.5看到的 http://www.trirand.com/jqgridwiki/doku.php?id=wiki:change#additions_and_changes )。您可以验证这个奇怪的方式工作。典型的附加参数末页)和记录不是我们的JSON数据里面存在,它们将被初始化为以下页:0,总:1,记录:0 。因此,我们无法使数据分页。您还可以扩大 jsonReader 与功能定义记录(也可作为功能),如

  jsonReader:{
    repeatitems:假的,
    ID:ID,
    根:函数(OBJ){返回OBJ; },
    页:功能(OBJ){返回1; },
    总:函数(OBJ){返回1; },
    记录:函数(OBJ){返回obj.length; }
}
 

这将完成我们的jsonReader。然后设定的rowNum:0 会不会更需要

予表明这种方式只显示jqGrid的的灵活性。你应该使用说明的方式只有当你访问一个Web服务器,你不能改变。 jqGrid的具有类似功能的页面排序的和2种的搜索的(更因此与在相应的选择过滤)的数据:简单和高级。如果我们希望我们的网页上有jqGrid的内这些不错的功能,我们应该在Web服务定义诸如

一个额外的方法

  [OperationContract的]
[WebGet(ResponseFormat = WebMessageFormat.Json,
        UriTemplate =jqGridGetTestbereiche _search = {_搜索}&放大器;页= {PAGE}&功放;+
                      行= {行}&放大器; SIDX = {sortIndex}&放大器; SORD = {sortDirection}&功放;+
                      searchField = {searchField}&放大器; searchString = {searchString}&功放;+
                      searchOper = {searchOper}&放大器;过滤器= {过滤器})]
公共jqGridTable jqGridGetMovies(
  INT页,INT行,字符串sortIndex,串sortDirection,
  串_search,串searchField,串searchString,
  串searchOper,串过滤器)
 

其中, jqGridTable

 公共类jqGridTable
{
    公众诠释共{获得;组; } //总页数
    公众诠释页{获得;组; } //电流从零开始的页码
    公众诠释记录{获得;组; } //记录总数
    公开名单&LT; jqGridRow&GT;行{获得;组; }
}
公共类jqGridRow
{
    公共字符串ID {获得;组; }
    公开名单&LT;字符串&GT;细胞{获得;组; }
}
 

或者,如果我们想使用从服务器传送到客户机然后数据的最紧凑的形式

  // jsonReader:{repeatitems:真,细胞:,ID:0}
公共类jqGridTable {
    公众诠释共{获得;组; } //总页数
    公众诠释页{获得;组; } //电流从零开始的页码
    公众诠释记录{获得;组; } //记录总数
    公开名单&LT;列表&LT;字符串&GT;&GT;行{获得;组; } //每一行的第一个元素必须是连续的编号。
}
 

(你可以阅读更多关于这种类型的数据传输在 HTTP:// WWW。 trirand.com/blog/jqgrid/jqgrid.html 如果您选择在左边的树部分数据映射,然后选择数据优化)

PS:关于jsonReader你可以阅读更多的 HTTP:/ /www.trirand.com/jqgridwiki/doku.php?id=wiki:retrieving_data#json_data 。我的一个老的回答<一href="http://stackoverflow.com/questions/2690657/mapping-json-data-in-jqgrid/2706620#2706620">http://stackoverflow.com/questions/2690657/mapping-json-data-in-jqgrid/2706620#2706620可也有趣的你。

更新2 :因为你没有标记的答案被接受,你留下了一些问题。所以,我在Visual Studio 2010中创建一个新的项目,该项目演示一下我写的。您可以从 http://www.ok-soft-gmbh.com下载源代码/jqGrid/jQueryMVC.zip 。与您的项目,尤其是完整的URL作为jqGrid的一个参数,web.config中的一部分,它描述了WCF服务接口部分进行比较。

更新1 :我用VS2010没有那么长的时间。所以,我可以很快降级这VS2008。因此,几乎在同一code工作在Visual Studio 2008的工作,但与ASP.NET MVC 2.0,你可以从的 http://www.ok-soft-gmbh.com/jqGrid/VS2008jQueryMVC.zip 。在code在ASP.NET MVC 1.0应该是一样的,但是从项目文件一个GUID,并从Web.config中一些字符串应进行修补(见的 http://www.asp.net/learn/whitepapers/aspnet-mvc2-upgrade-notes )。

This is a bit of a continuation of a previous question.

Now I'm trying to make a call to an AJAX enabled web service which I have defined within the ASP.NET MVC application (i.e. the MovieService.svc). But the service is never being called in my getMovies javascript function.

This same technique of calling the AJAX web service works ok if I try it in a non ASP.NET MVC application, so it makes me wonder if maybe the ASP MVC routes are interfering with things somehow when it tries to make the AJAX web service call.

Do you have any idea why my web service isn't getting called? Code below.

    <script src="<%= ResolveClientUrl("~/scripts/jquery-1.4.2.min.js") %>" type="text/javascript"></script>

    <script src="<%= ResolveClientUrl("~/scripts/grid.locale-en.js") %>" type="text/javascript"></script>

    <script src="<%= ResolveClientUrl("~/scripts/jquery-ui-1.8.1.custom.min.js") %>"
        type="text/javascript"></script>

    <script src="<%= ResolveClientUrl("~/scripts/jquery.jqGrid.min.js") %>" type="text/javascript"></script>

    <script type="text/javascript">
        var lastsel2;

        function successFunction(jsondata) {
            debugger
            var thegrid = jQuery("#editgrid");
            for (var i = 0; i < jsondata.d.length; i++) {
                thegrid.addRowData(i + 1, jsondata.d[i]);
            }
        }

        function getMovies() {
            debugger
            // ***** the MovieService#GetMovies method never gets called
            $.ajax({
                url: 'MovieService.svc/GetMovies',
                data: "{}",  // For empty input data use "{}",
                dataType: "json",
                type: "GET",
                contentType: "application/json; charset=utf-8",
                success: successFunction
            });
        }

        jQuery(document).ready(function() {
            jQuery("#editgrid").jqGrid({
                datatype: getMovies,
                colNames: ['id', 'Movie Name', 'Directed By', 'Release Date', 'IMDB Rating', 'Plot', 'ImageURL'],
                colModel: [
                  { name: 'id', index: 'Id', width: 55, sortable: false, hidden: true, editable: false, editoptions: { readonly: true, size: 10} },
                  { name: 'Movie Name', index: 'Name', width: 250, editable: true, editoptions: { size: 10} },
                  { name: 'Directed By', index: 'Director', width: 250, align: 'right', editable: true, editoptions: { size: 10} },
                  { name: 'Release Date', index: 'ReleaseDate', width: 100, align: 'right', editable: true, editoptions: { size: 10} },
                  { name: 'IMDB Rating', index: 'IMDBUserRating', width: 100, align: 'right', editable: true, editoptions: { size: 10} },
                  { name: 'Plot', index: 'Plot', width: 150, hidden: false, editable: true, editoptions: { size: 30} },
                  { name: 'ImageURL', index: 'ImageURL', width: 55, hidden: true, editable: false, editoptions: { readonly: true, size: 10} }
                ],
                pager: jQuery('#pager'),
                rowNum: 5,
                rowList: [5, 10, 20],
                sortname: 'id',
                sortorder: "desc",
                height: '100%',
                width: '100%',
                viewrecords: true,
                imgpath: '/Content/jqGridCss/redmond/images',
                caption: 'Movies from 2008',
                editurl: '/Home/EditMovieData/',
                caption: 'Movie List'
            });

            $("#bedata").click(function() {
                var gr = jQuery("#editgrid").jqGrid('getGridParam', 'selrow');
                if (gr != null)
                    jQuery("#editgrid").jqGrid('editGridRow', gr, { height: 280, reloadAfterSubmit: false });
                else
                    alert("Hey dork, please select a row");
            });            

        });

    </script>

    <h2>
        <%= Html.Encode(ViewData["Message"]) %></h2>
    <p>
        To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">
            http://asp.net/mvc</a>.
    </p>
    <table id="editgrid">
    </table>
    <div id="pager" style="text-align: center;">
    </div>
    <input type="button" id="bedata" value="Edit Selected" />

Here's my RegisterRoutes code:

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

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

Here's what my MovieService class looks like:

namespace jQueryMVC
{
    [ServiceContract(Namespace = "")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class MovieService
    {
        // Add [WebGet] attribute to use HTTP GET
        [OperationContract]
        [WebGet(ResponseFormat = WebMessageFormat.Json)]
        public IList<Movie> GetMovies()
        {
            return Persistence.GetMovies();
        }

    }
}

解决方案

Your main problem is that you use not absolute URLs in the ajax call. Wrong entries in web.config can make also problems. Moreover you use datatype: getMovies instead of datatype: 'json' and postData: yourData. The way with datatype as functions exist (see http://www.trirand.com/jqgridwiki/doku.php?id=wiki:retrieving_data#function), but since jqGrid 3.6.5 you have more direct way inside of jsonReader to read the data returned from web server.

UPDATED: It seems to me that describing of editing features I'll make later and explain here just how to get JSON data and fill there inside of jqGrid.

First of all jqGrid can request itself the JSON data from the server. So we don’t need to make a separate jQuery.ajax call. You need only define a URL which point to the server and define some additional jQuery.ajax parameters which you prefer. You don’t post in your question the definition of the Movie class. So I define it myself like following

public class Movie {
    public int Id { get; set; }
    public string Name { get; set; }
    public string Director { get; set; }
    public string ReleaseDate { get; set; }
    public string IMDBUserRating { get; set; }
    public string Plot { get; set; }
    public string ImageURL { get; set; }
}

You should remark, that Microsoft serialize DataTime type not as a readable date string but as a string /Date(utcDate)/, where utcDate is this number (see http://stackoverflow.com/questions/2794633/jquery-param-doesnt-serialize-javascript-date-objects/2794836#2794836). To make fewer problems at the beginning I define ReleaseDate as string.

Method IList<Movie> GetMovies() returns JSON data like an array of objects Movie. So jqGrid as a response to HTTP GET request receive from the MovieService.svc/GetMovies URL the data like following:

 [{"Id":1, "Name": "E.T.", "Director": "Steven Spielberg",...},{...},...]

I can say that it is not typical format of data, which are waiting jqGrid (compare with http://www.trirand.com/jqgridwiki/doku.php?id=wiki:retrieving_data#json_data). To be able to place the data inside of jqGrid we must define a jsonReader. So we do following

jQuery("#editgrid").jqGrid({
    url: '<%= Url.Content("~/MovieService.svc/GetMovies")%>',
    datatype: 'json',
    ajaxGridOptions: { contentType: "application/json" },
    jsonReader: { repeatitems: false, id: "Id", root: function(obj) { return obj; }},
    headertitles: true,
    sortable: true,
    colNames: ['Movie Name', 'Directed By', 'Release Date',
               'IMDB Rating', 'Plot', 'ImageURL'],
    colModel: [
        { name: 'Name', width: 250},
        { name: 'Director', width: 250, align: 'right' },
        { name: 'ReleaseDate', width: 100, align: 'right' },
        { name: 'IMDBUserRating', width: 100, align: 'right' },
        { name: 'Plot', width: 150 },
        { name: 'ImageURL', width: 55, hidden: true }
    ],
    pager: jQuery('#pager'),
    pginput: false,
    rowNum: 0,
    height: '100%',
    viewrecords: true,
    rownumbers: true,
    caption: 'Movies from 2008'
}).jqGrid('navGrid', '#pager', { add: false, edit: false, del: false, search: false });

REMARK: I remove from the example any sorting parameters, because in case of request of JSON data, the sorting parameter will be only send to server (some additional parameters append the server URL) and server must give back sorted data. For more information see description of prmNames parameter on http://www.trirand.com/jqgridwiki/doku.php?id=wiki:options and description of sopt parameter on http://www.trirand.com/jqgridwiki/doku.php?id=wiki:singe_searching.

With respect of datatype: 'json' we define dataType: 'json' parameter of jQuery.ajax (don’t confuse the case inside of datatype parameter). The names of all fields inside of colModel we define exact the same as the field names inside our JSON objects. Some additional parameters viewrecords, rownumbers, sortable and headertitles are not very important in this example, I choosed there because 1) I like there and 2) I set rowNum: 0 to make possible the options rownumbers: true works correct and not show us negative row numbers started with -5 if rowNum: 5 like in your original example.

With ajaxGridOptions: { contentType: "application/json" } we define additional parameters which will be direct forwarded to the jQuery.ajax.

The most complex part of this example is

jsonReader: { repeatitems: false, id: "Id", root: function(obj) { return obj; }}

It defines that id of all rows have the name "Id" (see definition of the class Movie). "repeatitems: false" say that every data field we want identify by the field name (defined in colModel) instead of default definition per position. The definition of root is a little strange, but it defines how to find the root of rows inside of JSON data. Default format of JSON data is following

{
  total: "xxx", 
  page: "yyy", 
  records: "zzz",
  rows : [
    {id:"1", cell:["cell11", "cell12", "cell13"]},
    {id:"2", cell:["cell21", "cell22", "cell23"]},
      ...
  ]
}

and the root of rows are defined as root: "rows". So if the JSON data assigned to the variable res, the root can be returned as res.rows. To allow jqGrid to read our data we define jsonReader.root as a function (this feature exist since jqGrid 3.6.5 see http://www.trirand.com/jqgridwiki/doku.php?id=wiki:change#additions_and_changes). You can verify that this strange method work. The typical additional parameters page, total (lastpage) and records are not exist inside of our JSON data and they will be initialized as following page:0, total:1, records:0. So we are not able to make data paging. You can expand jsonReader with functions defining page, total and records (also as functions) like

jsonReader: {
    repeatitems: false,
    id: "Id",
    root: function (obj) { return obj; },
    page: function (obj) { return 1; },
    total: function (obj) { return 1; },
    records: function (obj) { return obj.length; }
}

which will complete our jsonReader. Then setting of rowNum: 0 will not more needed.

I showed this way only to show the flexibility of jqGrid. You should use described way only if you access a web server which you cannot change. jqGrid has features like paging, sorting and two kind of searching (more as filtering with WHERE in the corresponding SELECT) of data: simple and advanced. If we want have these nice features inside of jqGrid on our web pages we should define in Web Service an additional method like

[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json,
        UriTemplate = "jqGridGetTestbereiche?_search={_search}&page={page}&"+
                      "rows={rows}&sidx={sortIndex}&sord={sortDirection}&"+
                      "searchField={searchField}&searchString={searchString}&"+
                      "searchOper={searchOper}&filters={filters}")]
public jqGridTable jqGridGetMovies(
  int page, int rows, string sortIndex, string sortDirection,
  string _search, string searchField, string searchString,
  string searchOper, string filters)

where jqGridTable

public class jqGridTable
{
    public int total { get; set; }      // total number of pages
    public int page { get; set; }       // current zero based page number
    public int records { get; set; }    // total number of records
    public List<jqGridRow> rows { get; set; }
}
public class jqGridRow
{
    public string id { get; set; }
    public List<string> cell { get; set; }
}

Or if we want use the most compact form of data transferred from server to client then

// jsonReader: { repeatitems : true, cell:"", id: "0" }
public class jqGridTable {
    public int total { get; set; }          // total number of pages
    public int page { get; set; }           // current zero based page number
    public int records { get; set; }        // total number of records
    public List<List<string>> rows { get; set; }// first element in every row must be id of row.
}

(you can read more about this kind of data transfer on http://www.trirand.com/blog/jqgrid/jqgrid.html if you choose on the left tree part "Data Mapping" and then "Data Optimization")

P.S.: About jsonReader you can read more on http://www.trirand.com/jqgridwiki/doku.php?id=wiki:retrieving_data#json_data. One my old answer http://stackoverflow.com/questions/2690657/mapping-json-data-in-jqgrid/2706620#2706620 can be also interesting for you.

UPDATED 2: Because you don't mark the answer as accepted, you stay have some problems. So I created a new Project in Visual Studio 2010 which demonstrate what I written. You can download the source from http://www.ok-soft-gmbh.com/jqGrid/jQueryMVC.zip. Compare with your project, especially the part with full url as a parameter of jqGrid and a part of web.config which describes WCF service interface.

UPDATED 3: I use VS2010 not so long time. So I could very quickly downgrade this to VS2008. So almost the same code working working in Visual Studio 2008, but with ASP.NET MVC 2.0 you can download from http://www.ok-soft-gmbh.com/jqGrid/VS2008jQueryMVC.zip. The code in ASP.NET MVC 1.0 should be the same, but a GUID from the project file and some strings from Web.config should be patched (see http://www.asp.net/learn/whitepapers/aspnet-mvc2-upgrade-notes).

这篇关于与jQuery的ASP.NET MVC - 呼吁支持AJAX的Web服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆