我将URL转换为用户友好,但问题是,它导致我的AJAX无法正常工作:它不是返回JSON,而是响应text/html; charset=utf-8
,任何想法?
的本地主机/主页/票?标签= 0 的
以
的本地主机/主页/票务/ 0 的
jquery Datatable
self.$('#tblticket').dataTable({
"bDestroy": true,
"bServerSide": true,
"sAjaxSource": '/Home/Ticket/AjaxHandler',
"fnServerParams": function (aoData){
aoData.push( { "name": "sStatus", "value": status } );
},
路由器
routes.MapRoute(
name: "TicketRoute",
url: "Ticket/{tab}",
defaults: new { controller = "Ticket", action = "Index", tab = UrlParameter.Optional }
);
更新1
如果我将路由器更改为此,它可以工作,但网址看起来像 本地主机/主页/票/索引/ 0 的。路由器干扰ajax呼叫,任何想法?我希望网址看起来像 localhost / Home / Ticket / 0 ,仍然能够进行ajax调用,我不知道,可以做些什么?
routes.MapRoute(
name: "TicketRoute",
url: "Ticket/Index/{tab}",
defaults: new { controller = "Ticket", action = "Index", tab = UrlParameter.Optional }
);
答案 0 :(得分:2)
在我的MVC4版本中,我做了以下内容:
在我的控制器中创建了一个DataTables可以访问的方法
[HttpGet]
public ActionResult GetRecords(jQueryDataTableParamModel param)
{
#region ViewModel Binding with TotalRecords count, pagination and search
List<vm_DataTable_TableName> model;
int totalRecords = 0;
using (DBEntities db = new DBEntities())
{
model = Mapper.Map(db.GetRecords(), new List<vm_DataTable_TableName>()); //Using AutoMapper for viewmodel bindings
totalRecords = model.Count();
}
#endregion
#region Filtration/Pagination
var filtered = ***Filter depending on your needs***
var displayed = filtered.Skip(param.iDisplayStart).Take(param.iDisplayLength);
#endregion
#region Convert Result to String Array for JSON Conversion/Trim excess white space to reduce size of result
IEnumerable<string[]> result = new List<string[]>();
result = displayed
.Select(s => new string[] {
(!string.IsNullOrEmpty(Convert.ToString(s.ID))) ? s.ID.ToString().Trim() : string.Empty,
(!string.IsNullOrEmpty(s.val_1)) ? s.val_1.Trim() : string.Empty,
(!string.IsNullOrEmpty(s.val_2)) ? s.val_2.Trim() : string.Empty,
(!string.IsNullOrEmpty(s.val_3)) ? s.val_3.Trim() : string.Empty
});
#endregion
return Json(new
{
sEcho = param.sEcho,
iTotalRecords = totalRecords,
iTotalDisplayRecords = filtered.Count(),
aaData = result
},
JsonRequestBehavior.AllowGet);
}
在jQuery DataTables初始化中:
$('#tblticket').dataTable({
"bDestroy": true,
"bServerSide": true,
"sAjaxSource": '@Url.Content("~/Home/Ticket/GetRecords")', //Server inserted url
"fnServerData": function Data(sSource, aoData, fnCallback) {
$.ajax({
"dataType": "json",
"contentType": "application/json; charset=utf-8",
"type": "GET",
"url": sSource,
"data": aoData,
"success":
function (msg) {
//Whatever other actions you want to do with the data
fnCallback(msg);
},
"failure":
function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.status);
alert(XMLHttpRequest.responseText);
}
});
}
});
'@ Url.Content(“”)'在使用MVC区域时也很友好。
当我第一次使用这个插件时,These系列文章给了我很多帮助。