2016-11-06 2 views
0

Я использую JQuery Datatable 1.10.12 с использованием серверной части с возможностью обработки. Я пробовал код со своего сайта JQuery Data table server side, но без везения. Я делаю что-то неправильно, какая страница не показывает записи и дает ошибку 500. Любая помощь будет отличной.JQuery DataTable с серверной стороны с использованием asmx

Мой код:

.aspxpage

<script> 
    $(document).ready(function() { 
     $('#example').DataTable({ 
      serverSide: true, 
      ajax: 'EmployeeService.asmx/GetPersons' 
     }); 
     });  
     </script> 
    <body> 
    <table id="example" class="display" cellspacing="0" width="100%"> 
    <thead> 
     <tr> 
      <th>BusinessEntityID</th> 
      <th>FirstName</th> 
      <th>MiddleName</th> 
      <th>LastName</th> 
      <th>PersonType</th> 
     </tr> 
    </thead>  
    </table>  
    </body> 

    asmx: 
    [WebMethod] 
    public void GetPersons(int iDisplayLength, int iDisplayStart, int iSortCol_0, string sSortDir_0, string sSearch) 

    { 
     int displayLength = iDisplayLength; 
     int displayStart = iDisplayStart; 
     int sortCol = iSortCol_0; 
     string sortDir = sSortDir_0; 
     string search = sSearch; 
     List<Person> pdetails = new List<Person>(); 
     int filteredcount = 0; 
     using (SqlConnection con = new SqlConnection("Data Source=xxx;Initial Catalog=AdventureWorks;Integrated Security=True")) 
     { 
      SqlCommand cmd = new SqlCommand(("spGetPersons"), con); 
      cmd.CommandType = CommandType.StoredProcedure; 

      SqlParameter pDisplayLength = new SqlParameter() 
      { 
       ParameterName = "@DisplayLength", 
       Value = displayLength 
      }; 
      cmd.Parameters.Add(pDisplayLength); 
      SqlParameter pDisplayStart = new SqlParameter() 
      { 
       ParameterName = "@DisplayStart", 
       Value = displayStart 
      }; 
      cmd.Parameters.Add(pDisplayStart); 
      SqlParameter pSortCol = new SqlParameter() 
      { 
       ParameterName = "@SortCol", 
       Value = sortCol 
      }; 
      cmd.Parameters.Add(pSortCol); 
      SqlParameter pSortDir = new SqlParameter() 
      { 
       ParameterName = "@SortDir", 
       Value = sortDir 
      }; 
      cmd.Parameters.Add(pSortDir); 
      SqlParameter pSearchString = new SqlParameter() 
      { 
       ParameterName = "@Search", 
       Value = string.IsNullOrEmpty(search)?null:search 
      }; 
      cmd.Parameters.Add(pSearchString); 
      con.Open(); 
      SqlDataReader rdr = cmd.ExecuteReader(); 
      while (rdr.Read()) 
      { 
       Person per = new Person(); 
       per.BusinessEntityID = rdr["BusinessEntityID"].ToString(); 
       filteredcount = Convert.ToInt32(rdr["TotalCount"].ToString()); 
       per.FirstName = rdr["FirstName"].ToString(); 
       per.MiddleName = rdr["MiddleName"].ToString(); 
       per.LastName = rdr["LastName"].ToString(); 
       per.PersonType = rdr["PersonType"].ToString(); 
       pdetails.Add(per); 
      } 
     } 

     var result = new 
     { 

      draw = 1, 
      recordsTotal = GetPersonsTotalCount(), 
      recordsFiltered = filteredcount, 
      data = pdetails 
     }; 

     JavaScriptSerializer js = new JavaScriptSerializer(); 
     js.MaxJsonLength = 2147483644; 
     Context.Response.Write(js.Serialize(result)); 
    } 

    private int GetPersonsTotalCount() 
    { 
     int totalPersonCount = 0; 
     using (SqlConnection con = new SqlConnection("Data Source=xxx;Initial Catalog=AdventureWorks;Integrated Security=True")) 
     { 
      SqlCommand cmd = new SqlCommand(("select count(*) from Person.Person"), con); 
      con.Open(); 
      totalPersonCount = (int)cmd.ExecuteScalar(); 
     } 
     return totalPersonCount; 
    } 
    public class Person 
    { 
     public string BusinessEntityID { get; set; } 
     public string FirstName { get; set; } 
     public string MiddleName { get; set; } 
     public string LastName { get; set; } 
     public string PersonType { get; set; } 

    } 

    JSON : 

    {"draw":1,"recordsTotal":19972,"recordsFiltered":19972,"data":[{"BusinessEntityID":"1","FirstName":"Ken","MiddleName":"J","LastName":"Sánchez","PersonType":"EM"},{"BusinessEntityID":"2","FirstName":"Terri","MiddleName":"Lee","LastName":"Duffy","PersonType":"EM"},{"BusinessEntityID":"3","FirstName":"Roberto","MiddleName":"","LastName":"Tamburello","PersonType":"EM"},{"BusinessEntityID":"4","FirstName":"Rob","MiddleName":"","LastName":"Walters","PersonType":"EM"},{"BusinessEntityID":"5","FirstName":"Gail","MiddleName":"A","LastName":"Erickson","PersonType":"EM"},{"BusinessEntityID":"6","FirstName":"Jossef","MiddleName":"H","LastName":"Goldberg","PersonType":"EM"},{"BusinessEntityID":"7","FirstName":"Dylan","MiddleName":"A","LastName":"Miller","PersonType":"EM"},{"BusinessEntityID":"8","FirstName":"Diane","MiddleName":"L","LastName":"Margheim","PersonType":"EM"},{"BusinessEntityID":"9","FirstName":"Gigi","MiddleName":"N","LastName":"Matthew","PersonType":"EM"},{"BusinessEntityID":"10","FirstName":"Michael","MiddleName":"","LastName":"Raheem","PersonType":"EM"}]} 

ОШИБКА:

http://localhost:64400/EmployeeService.asmx/GetPersons?draw=1&columns%5B0%5 …art=0&length=10&search%5Bvalue%5D=&search%5Bregex%5D=false&_=1478471333896 Failed to load resource: the server responded with a status of 500 (Internal Server Error) Server Error in '/' Application.

Request format is unrecognized for URL unexpectedly ending in '/GetPersons'.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: Request format is unrecognized for URL unexpectedly ending in '/GetPersons'.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[InvalidOperationException: Request format is unrecognized for URL unexpectedly ending in '/GetPersons'.]
System.Web.Services.Protocols.WebServiceHandlerFactory.CoreGetHandler(Type type, HttpContext context, HttpRequest request, HttpResponse response) +169669 System.Web.Services.Protocols.WebServiceHandlerFactory.GetHandler(HttpContext context, String verb, String url, String filePath) +209
System.Web.Script.Services.ScriptHandlerFactory.GetHandler(HttpContext context, String requestType, String url, String pathTranslated) +120
System.Web.MaterializeHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +339 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

ответ

0

Пожалуйста, измените ASMX FIle как

[WebMethod] 
[ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
[ScriptMethod(UseHttpGet=true)] 
    public void GetPersons(int iDisplayLength, int iDisplayStart, int iSortCol_0, string sSortDir_0, string sSearch) 

{ 
} 

Modifi веб-конфигурации добавить протоколы в webServ листы

<system.web> 
<webServices> 
     <protocols> 
     <add name="HttpGet"/> 
     <add name="HttpPost"/> 
     </protocols> 
+0

Hi Rajshee. Спасибо за помощь и код. У меня есть [System.Web.Script.Services.ScriptService] в моем xxx. Файл asmx.cs. [System.Web.Script.Services.ScriptService] общественного класса ABCDetailService: System.Web.Services.WebService {[WebMethod] [ScriptMethod (UseHttpGet = верно, ResponseFormat = ResponseFormat.Json)] общественных недействительный GetPersons (интермедиат iDisplayLength , int iDisplayStart, int iSortCol_0, строка sSortDir_0, строка sSearch) {} –

+0

вы можете разместить полный код asmx-файла.? –

+0

ОШИБКА: System.InvalidOperationException: Отсутствует параметр: iDisplayLength. в System.Web.Services.Protocols.ValueCollectionParameterReader.Read (коллекция NameValueCollection) в System.Web.Services.Protocols.HttpServerProtocol.ReadParameters() в System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest() –