An invalid request URI was provided. The request URI must either be an absolute URI or BaseAddress must be set.
这是Api控制器:
EmailTemplate.UI\Areas\Ticket\Api\TicketController.cs
这是代码:
var client = new HttpClient();
string _url = _apiTicket + "Areas/Ticket/Api/TicketController/Get/10?PageIndex=" + pageIndex + "&PageSize=" + pageSize;
var response = client.GetAsync(_url).Result;
var result1 = response.Content.ReadAsStringAsync().Result;
这里作为回应,这个错误来了。
我想通过pageIndex和pagesize在datatable服务器端mvc 4中过滤数据。
以下是api中的方法:
public HttpResponseMessage Get1(int UserId)
{
string _searchString = GetQueryValueByName.Get(Request.GetQueryNameValuePairs(), "searchstr");
int _start = int.Parse(GetQueryValueByName.Get(Request.GetQueryNameValuePairs(),"start"));
int _length =int.Parse(GetQueryValueByName.Get(Request.GetQueryNameValuePairs(),"length"));
List<sp_Ticketlist_Result> _dbData;
int _dataTotaRowCount;
_dbData = _repository.GetTicket(UserId).ToList();
_dataTotaRowCount = _dbData.Count();
if (!string.IsNullOrEmpty(_searchString))
{
_dbData = _dbData.Where(m =>
m.Name.ToUpper().Contains(_searchString.ToUpper())).ToList();
_dataTotaRowCount = _dbData.Count();
_dbData = _dbData.Skip(_start).Take(_length).ToList();
}
else
{
_dbData = _dbData.Skip(_start).Take(_length).ToList();
}
return Request.CreateResponse(HttpStatusCode.OK,DataTableObjectConverter.ConvertData(_dbData, _dataTotaRowCount));
}
public static class GetQueryValueByName
{
public static string Get(IEnumerable<KeyValuePair<string, string>> _req,
string key)
{
return _req.FirstOrDefault(ma => string.Compare(ma.Key, key) ==
0).Value;
}
}
public static class DataTableObjectConverter
{
public static DataTableObject ConvertData<T>(T source, int count)
where T : class, new()
{
DataTableObject _obj = new DataTableObject();
//_obj.draw = 1;
_obj.recordsFiltered = count;
_obj.recordsTotal = count;
_obj.data = source;
return _obj;
}
}
是否需要使用pageIndex和pagesize的任何方法?
如何通过pageIndex和pagesize在方法中定义数据?
这是我的GetData方法:
public ActionResult GetData()
{
// Initialization.
JsonResult result = new JsonResult();
try
{
// Initialization.
string search = Request.Form.GetValues("search[value]")[0];
string draw = Request.Form.GetValues("draw")[0];
string order = Request.Form.GetValues("order[0][column]")[0];
string orderDir = Request.Form.GetValues("order[0][dir]")[0];
int startRec = Convert.ToInt32(Request.Form.GetValues("start")[0]);
// int pageSize = Convert.ToInt32(Request.Form.GetValues("length")[0]);
var start = Request.Form.GetValues("start").FirstOrDefault();
var length = Request.Form.GetValues("length").FirstOrDefault();
int pageSize = length != null ? Convert.ToInt32(length) : 0;
int recordStatr = start != null ? Convert.ToInt32(start) : 0;
recordStatr = recordStatr == 0 ? 1 : recordStatr;
var pageIndex = (recordStatr / pageSize) + 1;
int recordsTotal = 0;
// Loading.
List<AppTicket> data = this.LoadData();
// Total record count.
int totalRecords = data.Count;
// Verification.
//if (!string.IsNullOrEmpty(search) &&
// !string.IsNullOrWhiteSpace(search))
//{
// // Apply search
// data = data.Where(p => p.Title.ToString().ToLower().Contains(search.ToLower()) ||
// p.Name.ToLower().Contains(search.ToLower()) ||
// p.Email.ToString().ToLower().Contains(search.ToLower())).ToList();
// //p.ProductName.ToLower().Contains(search.ToLower()) ||
// //p.SpecialOffer.ToLower().Contains(search.ToLower()) ||
// //p.UnitPrice.ToString().ToLower().Contains(search.ToLower()) ||
// //p.UnitPriceDiscount.ToString().ToLower().Contains(search.ToLower())).ToList();
//}
// Sorting.
data = this.SortByColumnWithOrder(order, orderDir, data);
// Filter record count.
int recFilter = data.Count;
// Apply pagination.
// data = data.Skip(startRec).Take(pageSize).ToList();
// Loading drop down lists.
// result = this.Json(new { draw = Convert.ToInt32(draw), recordsTotal = totalRecords, recordsFiltered = recFilter, data = data }, JsonRequestBehavior.AllowGet);
//Find Order Column
//var sortColumn = Request.Form.GetValues("columns[" + Request.Form.GetValues("order[0][column]").FirstOrDefault() + "][name]").FirstOrDefault();
//var sortColumnDir = Request.Form.GetValues("order[0][dir]").FirstOrDefault();
var client = new HttpClient();
//client.BaseAddress = new Uri("http://localhost:1849");
//client.DefaultRequestHeaders.Accept.Clear();
// client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// string _url = _apiTicket + ".Get?UserId=" + 10 + "&PageIndex=" + pageIndex + "&PageSize=" + pageSize;
//var response = client.GetAsync(_url).Result;
//var response1 = client.GetAsync("/Areas/Ticket/Api/Get/10,10,10").Result;
//if (response1.IsSuccessStatusCode)
//{
// string responseString = response.Content.ReadAsStringAsync().Result;
//}
// string _url = _apiTicket + "Get1/10?searchstr=Monaj&PageIndex=" + pageIndex + "&PageSize=" + pageSize;
// string apiUrl = "Api/Ticket/10?searchstr=Monaj&PageIndex=" + pageIndex + "&PageSize=" + pageSize;
string apiUrl = "../Areas/api/Ticket/1?searchstr=Monaj&start=0&length=10";
var response = client.GetAsync(apiUrl).Result;
var result1 = response.Content.ReadAsStringAsync().Result;
// HttpResponseMessage response = await client.GetAsync(_url);
// HttpResponseMessage response = client.GetAsync(_url).Result;
//var response = client.GetAsync(_url).Result;
// var result1 = response.Content.ReadAsStringAsync().Result;
JsonResult jsonresult = Json(result1, JsonRequestBehavior.AllowGet);
AppTicket _contacts = new AppTicket();
_contacts = JsonConvert.DeserializeObject<AppTicket>(jsonresult.Data.ToString());
//return Json(new { draw = draw, recordsFiltered = recordsTotal, recordsTotal = recordsTotal, data = _contacts.listcourses }, JsonRequestBehavior.AllowGet);
result = this.Json(new { draw = Convert.ToInt32(draw), recordsFiltered = totalRecords, recordsTotal = recordsTotal, data = data }, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
// Info
Console.Write(ex);
}
// Return info.
return result;
}
我在custom-datatable.js中使用json ajax。 这是代码:
$(document).ready(function ()
{
debugger
$('#TableId').DataTable(
{
//"columnDefs": [
// { "width": "5%", "targets": [0] },
// {
// "className": "text-center custom-middle-align",
// "targets": [0, 1, 2, 3, 4, 5, 6]
// },
//],
'columnDefs': [{
'targets': 0,
'searchable': false,
'orderable': false,
'width': '1%',
'className': 'dt-body-center',
'render': function (data, type, full, meta) {
return '<input type="checkbox">';
}
}
,
{
targets: 2,
render: function (data, type, row, meta) {
if (type === 'display') {
data = '<a href="/TicketTemplate/AppDetails/' + row.Id + ' " >' + data + '</a>';
}
return data;
}
},
{
targets: 1,
render: function (data, type, row, meta) {
return moment(data).format('DD/MM/YYYY HH:mm:ss');
}
}
],
"language":
{
"processing": "<div class='overlay custom-loader-background'><i class='fa fa-cog fa-spin custom-loader-color'></i></div>"
},
"processing": true,
"serverSide": true,
"ajax":
{
"url": "/TicketTemplate/GetData",
"type": "POST",
"dataType": "JSON"
},
"columns": [
{ "data": '' },
{ "data": "CreatedDate" },
{ "data": "Title" },
//{
// //"data": "title",
// "render": function (data, type, row, meta) {
// //return '<a href=\"' + title + '\">' + title + '</a>';
// return '<a href="' + title + '">' + data + '</a>';
// }
//},
//{
//{
// //"data": "title",
// "render": function (data, type, row, meta) {
// //return '<a href=\"' + title + '\">' + title + '</a>';
// return "<a href=" + "/" + "/TicketTemplate/AppDetails/" + row.Id + " id=" + row.Id + ">" + row.Title + " </a>";
// }
//},
{ "data": "Name" },
{ "data": "Email" },
{ "data": "AssignTo" },
{ "data": "Status" }
]
});
});
首先它击中Mvc控制器GetData()并在GetData()中调用Api控制器Get()。 分页搜索全部是动态使用api。
答案 0 :(得分:0)
正如您在评论中提到的,&#34; 我想调用数据表分页排序搜索MVC控制器和web api控制器&#34;然后我建议做像这样,这就是我在许多项目中所做的。
//This is my API Get method
public HttpResponseMessage Get(int id)
{
string _searchString =
GetQueryValueByName.Get(Request.GetQueryNameValuePairs(), "searchstr");
int _start =
int.Parse(GetQueryValueByName.Get(Request.GetQueryNameValuePairs(),
"start"));
int _length =
int.Parse(GetQueryValueByName.Get(Request.GetQueryNameValuePairs(),
"length"));
List<sp_Ticketlist_Result> _dbData;
int _dataTotaRowCount;
_dbData = _repository.GetTicket(id).ToList();
_dataTotaRowCount = _dbData.Count();
if (!string.IsNullOrEmpty(_searchString))
{
_dbData = _dbData.Where(m =>
m.Name.ToUpper().Contains(_searchString.ToUpper())).ToList();
_dataTotaRowCount = _dbData.Count();
_dbData = _dbData.Skip(_start).Take(_length).ToList();
}
else
{
_dbData = _dbData.Skip(_start).Take(_length).ToList();
}
return Request.CreateResponse(HttpStatusCode.OK,
DataTableObjectConverter.ConvertData(_dbData, _dataTotaRowCount));
}
Bellow是我的GetQueryValueByName和DataTableObjectConverter类,我保存在一个单独的类文件中,只是引用我的Api控制器。
public static class GetQueryValueByName
{
public static string Get(IEnumerable<KeyValuePair<string, string>> _req,
string key)
{
return _req.FirstOrDefault(ma => string.Compare(ma.Key, key) ==
0).Value;
}
}
public static class DataTableObjectConverter
{
public static DataTableObject ConvertData<T>(T source, int count)
where T : class, new()
{
DataTableObject _obj = new DataTableObject();
//_obj.draw = 1;
_obj.recordsFiltered = count;
_obj.recordsTotal = count;
_obj.data = source;
return _obj;
}
}
public class DataTableObject
{
public int recordsTotal { get; set; }
public int recordsFiltered { get; set; }
public Object data { get; set; }
}
然后我的网址就像这样,
string apiUrl = "http://localhost:55442/api/Ticket/1?
searchstr=Monaj&start=0&length=10";
var client = new HttpClient();
var response = client.GetAsync(apiUrl).Result;
var result1 = response.Content.ReadAsStringAsync().Result;
注意:请参阅,此处我将开始,长度,搜索字符串作为查询字符串传递,并且我在我的Api Get方法中提取它们。只需更新您的网址,不要在查询字符串参数中提供 / 。你写的是这样的,
" + pageIndex + "/PageSize=" + pageSize;
这是错误的。检查我是怎么做的。您需要通过&amp;
分隔