这是previous问题的延续。
现在,我试图调用已在ASP.NET MVC应用程序(即MovieService.svc
)中定义的启用AJAX的Web服务。但是,从未在我的getMovies
javascript函数中调用该服务。
如果我在非ASP.NET MVC应用程序中尝试该调用AJAX Web服务的相同技术,则可以正常工作,因此它使我怀疑ASP MVC路由在尝试进行AJAX Web服务调用时是否会以某种方式干扰事物。 。
您是否知道为什么没有调用我的Web服务?下面的代码。
<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" />
这是我的RegisterRoutes代码:
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
);
}
这是我的MovieService类的样子:
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();
}
}
}
最佳答案
您的主要问题是在ajax
调用中没有使用绝对URL。 web.config
中的错误条目也会引起问题。此外,您使用datatype: getMovies
而不是datatype: 'json'
和postData: yourData
。存在使用datatype
作为函数的方式(请参见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
参数。
您没有在问题中发布Movie
类的定义。所以我自己定义如下
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; }
}
您应注意,Microsoft序列化
DataTime
类型不是可读的日期字符串,而是字符串/Date(utcDate)/
,其中utcDate
是此数字(请参见jQuery.param() - doesn't serialize javascript Date objects?)。为了在一开始就减少问题,我将
ReleaseDate
定义为字符串。方法
IList<Movie> GetMovies()
返回JSON数据,如对象Movie
的数组。因此,jqGrid作为对HTTP GET
请求的响应,从MovieService.svc/GetMovies
URL接收数据,如下所示: [{"Id":1, "Name": "E.T.", "Director": "Steven Spielberg",...},{...},...]
我可以说这不是等待jqGrid的典型数据格式(与http://www.trirand.com/jqgridwiki/doku.php?id=wiki:retrieving_data#json_data比较)。为了能够将数据放置在jqGrid中,我们必须定义一个
jsonReader
。所以我们做以下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 });
备注:我从示例中删除了任何排序参数,因为在请求JSON数据的情况下,排序参数将仅发送到服务器(某些附加参数附加在服务器URL上),并且服务器必须返回已排序的数据。有关更多信息,请参见http://www.trirand.com/jqgridwiki/doku.php?id=wiki:options上的
prmNames
参数说明和http://www.trirand.com/jqgridwiki/doku.php?id=wiki:singe_searching上的sopt
参数说明。关于
datatype: 'json'
,我们定义dataType: 'json'
的jQuery.ajax
参数(不要混淆datatype
参数内部的大小写)。我们在colModel
中定义的所有字段的名称与在JSON对象中定义的字段名称完全相同。在此示例中,一些其他参数viewrecords
,rownumbers
,sortable
和headertitles
不是很重要,我之所以选择了该参数,是因为1)我喜欢那里,以及2)设置rowNum: 0
以使选项rownumbers: true
像您的原始示例一样,不会向我们显示以-5开头的负行号。使用
rowNum: 5
,我们定义了其他参数,这些参数将直接转发到ajaxGridOptions: { contentType: "application/json" }
。此示例最复杂的部分是
jsonReader: { repeatitems: false, id: "Id", root: function(obj) { return obj; }}
它定义所有行的id都具有名称“ Id”(请参见
jQuery.ajax
的定义)。 “ class Movie
”表示我们要通过字段名称(在repeatitems: false
中定义)标识每个数据字段,而不是通过每个位置的默认定义来标识。 colModel
的定义有点奇怪,但是它定义了如何在JSON数据中查找行的根。以下是JSON数据的默认格式{
total: "xxx",
page: "yyy",
records: "zzz",
rows : [
{id:"1", cell:["cell11", "cell12", "cell13"]},
{id:"2", cell:["cell21", "cell22", "cell23"]},
...
]
}
行的根定义为
root
。因此,如果将JSON数据分配给变量root: "rows"
,则根可以作为res
返回。为了允许jqGrid读取我们的数据,我们将res.rows
定义为一个函数(此功能自jqGrid 3.6.5开始存在,请参见http://www.trirand.com/jqgridwiki/doku.php?id=wiki:change#additions_and_changes)。您可以验证此奇怪的方法是否有效。典型的附加参数jsonReader.root
,page
(total
)和lastpage
在我们的JSON数据中不存在,它们将按照records
进行初始化。因此,我们无法进行数据分页。您可以使用定义page:0, total:1, records:0
,jsonReader
和page
的函数(也可以作为函数)扩展total
,例如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; }
}
这将完成我们的jsonReader。然后,将不再需要设置
records
。我展示这种方式只是为了展示jqGrid的灵活性。仅当您访问无法更改的Web服务器时,才应使用描述的方式。 jqGrid具有分页,排序和两种数据搜索(更多的是在相应的SELECT中使用WHERE进行过滤)的功能:简单和高级。如果我们希望在网页上的jqGrid内具有这些出色的功能,则应在Web Service中定义其他方法,例如
[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)
其中
rowNum: 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<jqGridRow> rows { get; set; }
}
public class jqGridRow
{
public string id { get; set; }
public List<string> cell { get; set; }
}
或者,如果我们要使用从服务器到客户端的最紧凑形式的数据传输,则
// 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.
}
(如果您在左侧树部分中选择“数据映射”,然后选择“数据优化”,则可以在http://www.trirand.com/blog/jqgrid/jqgrid.html上阅读有关这种数据传输的更多信息)
附注:关于jsonReader,您可以在http://www.trirand.com/jqgridwiki/doku.php?id=wiki:retrieving_data#json_data上阅读更多内容。我的旧答案Mapping JSON data in JQGrid之一可能对您也很有趣。
更新2:因为您没有将答案标记为已接受,所以您会遇到一些问题。因此,我在Visual Studio 2010中创建了一个新项目,以演示我编写的内容。您可以从http://www.ok-soft-gmbh.com/jqGrid/jQueryMVC.zip下载源。与您的项目进行比较,尤其是将带有完整url的部分作为jqGrid的参数以及将web.config的一部分描述为WCF服务接口的部分。
更新3:我使用VS2010的时间不长。因此,我可以很快将其降级为VS2008。因此,几乎相同的代码在Visual Studio 2008中都能正常工作,但是使用ASP.NET MVC 2.0时,您可以从http://www.ok-soft-gmbh.com/jqGrid/VS2008jQueryMVC.zip下载。 ASP.NET MVC 1.0中的代码应该相同,但是应该修补项目文件中的GUID和Web.config中的某些字符串(请参见http://www.asp.net/learn/whitepapers/aspnet-mvc2-upgrade-notes)。
关于jquery - 使用ASP.NET MVC进行jquery-调用启用了Ajax的Web服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2835957/