2017-05-27 8 views
0

ASP.NET Core MVCプロジェクトでjquery-datatablesを学習しています。問題は、データ型がサーバー側のアクションメソッドを呼び出さないことです。Jqueryのデータ型はサーバー側でコントローラ内でアクションを呼び出さない

CrudController

[HttpPost] 

public object GetStudents() 
{ 
    var test = student.GetAll(10, 0); //List<Student> the count result is 2 
    return new { 
     draw = 2, 
     recordsTotal = 2, 
     recordsFiltered = 2, 
     data = test 
    }; 
} 

public IActionResult Index() 
{ 
    return View(); 
} 

HTML for IActionResult Index

<table id="example"> 
    <thead> 
     <tr> 
      <th>ID</th> 
      <th>Name</th> 
      <th>Birthdate</th> 
      <th>Active</th> 
     </tr> 
    </thead> 
</table> 

Script for datatables inside $(document).ready

$("#example").DataTable({ 
       "processing": true, 
       "serverSide": true, 
       "ajax": { 
        url: "@Url.Action("GetStudents", "Crud")", 
        type: "POST" 
       }, 
       "columns": [ 
         { "data": "id" }, 
         { "data": "name" }, 
         { "data": "birthdate" }, 
         { "data": "active" } 
       ] 
     }); 

上記のコードはエラーを発生しません。しかし、GetStudents()メソッドは呼び出されません(ブレークポイントを設定します)。何が問題なの?

+0

url: "/ Crud/GetStudents" –

+0

@AsifRazaの提案に基づいてURLを変更しましたか?コントローラとメソッドだけでなく、完全なURLを指定する必要があるかもしれません。 – markpsmith

答えて

0

あなたのコントローラの定義はちょっと間違っています。

それはまた、要求を検査するためにクロム/シオマネキのネットワーク]タブを使用し

$(document).ready(function() { 
    $('#example').DataTable({ 
     "ajax": { 
      "url": "/Crud/GetStudents", 
      "dataSrc": "" 
     }, 
     "columns": [{ 
      "data": "some col" 
     }, { 
      "data": "some other col" 
     }, 
     .... ] 
    }); 
}); 

クライアント側に続いてJSONデータに

public class CrudController : Controller 
    {    
     public ActionResult Index() 
     { 
      return View(); 
     } 
     public JsonResult GetStudents() 
     { 
      try 
      { 
       var result = <data list> 
       return Json(result, JsonRequestBehavior.AllowGet);      
      } 
      catch (Exception ex) 
      { 
       //Log ex.Message 
      } 
     } 
    } 

を返す必要があります。

+0

メソッド 'GetStudents'は、データテーブルによって呼び出されません。一方、 '$ .getJSON'を使って呼び出すことに成功しました。問題は戻り値ではなく、データ型がこのメソッドを呼び出せない理由です。 – derodevil

+0

私の言ったようなやり方を試しましたか?コントローラーが実際にjsonを返すべきオブジェクトを返しています –

+0

はい。それはまだ動作しません – derodevil

関連する問題