2013-06-05 34 views
1

在我的控制器中,我有以下方法..非常簡單。C#MVC4 - 通過自定義類的列表返回到Javascript

namespace Playground.Controllers 
{ 
    public class TasksController : Controller 
    { 

     // an ajax call to this generates the server error in the response 
     // "Value cannot be null. Parameter name: controllerContext" 
     [HttpGet] 
     public JsonResult GetTask() 
     { 
      List<Task> tasks = GetTasks(); 
      return Json(tasks, JsonRequestBehavior.AllowGet); 
     } 

     // an ajax call to this comes back successful, but only outputs 
     // "System.Collections.Generic.List`1[Playground.Models.Task]" 
     // which, when expanded... is empty 
     [HttpGet] 
     public List<Task> GetTasks() 
     { 
      //Create an array to hold all of the task objects 
      var tasks = new List<Task> { }; 

      //Execute the select statement and get back a SqlDataReader object 
      DataTable table = DataAccess.ExecuteSelect("select Id, Name, Description, Starting, Ending from Tasks"); 

      foreach (DataRow dr in table.Rows) 
      { 
       //Assign values to the task object 
       Task task = new Task((int)dr["Id"], 
            (string)dr["Name"], 
            (string)dr["Description"], 
            (DateTime)dr["Starting"], 
            (DateTime)dr["Ending"]); 

       //Add task object to list of task objects 
       tasks.Add(task); 
      } 

      return tasks; 
     } 

    } 
} 

它創建一個Task類型的對象。此處顯示的類

namespace Playground.Models 
{ 
    public class Task : Controller 
    { 
     public int Id { get; set; } 
     public string Name { get; set; } 
     public string Description { get; set; } 
     public DateTime Starting { get; set; } 
     public DateTime Ending { get; set; } 

     public Task(int Id, string Name, string Description, DateTime Starting, DateTime Ending) 
     { 
      this.Id = Id; 
      this.Name = Name; 
      this.Description = Description; 
      this.Starting = Starting; 
      this.Ending = Ending; 
     } 
    } 
} 

我對該方法有Ajax調用。

$.ajax({ 

    type: "GET", 
    url: "Tasks/GetTasks", //Changed between GetTasks and GetTask for testing. 
    dataType: "html", 
    //dataType: "json", 
    async: false, 
    data: { }, 
    success: function (data, text) { 

     console.dir(data); 
     console.dir(text); 

    }, 
    error: function (request, status, error) { 
     //do something 
    } 

}); 

來自兩個console.dir()的輸出線:

System.Collections.Generic.List`1[Playground.Models.Task] 
      No Properties 
      Tasks.js:12 
    success 
      No Properties 
      Tasks.js:13 

我如何得到一個Javascript對象數組中,我可以通過每一個「任務」環......到根據需要輸出「Id」,「Name」(等)?

我在C#中嘗試了各種組合,以我的任務列表轉換沒有成功

//Error on the Serialize line 
    // "Exception has been thrown by the target of an invocation." 
    public JsonResult GetTask() 
    { 
     List<Task> tasks = GetTasks(); 
     JavaScriptSerializer ser = new JavaScriptSerializer(); 
     object obj = tasks; 
     var val = ser.Serialize(obj); 
     return Json(val, JsonRequestBehavior.AllowGet); 
    } 

    --- AND --- 

    //Returns a server error to JS 
    //Value cannot be null. Parameter name: controllerContext 
    public JsonResult GetTask() 
    { 
     List<Task> tasks = GetTasks(); 
     JsonResult jr = new JsonResult(); 
     jr.Data = Json(tasks); 
     jr.JsonRequestBehavior = JsonRequestBehavior.AllowGet; 
     return jr; 
    } 

    --- AND --- 

    //Returns a server error to JS 
    //Value cannot be null. Parameter name: controllerContext 
    public JsonResult GetTask() 
    { 
     List<Task> tasks = GetTasks(); 
     return Json(tasks, JsonRequestBehavior.AllowGet); 
    } 

    --- AND --- 

    //Returns a server error to JS 
    //Value cannot be null. Parameter name: controllerContext 
    [HttpGet] 
    public JsonResult GetTask() 
    { 
     Task task = new Task(0, "Name", "Desc", new DateTime(), new DateTime()); 
     return Json(task, JsonRequestBehavior.AllowGet); 
    } 
+0

您應該已經擁有了它們。嘗試輸出'console.dir(data [0] .Id);'你會得到什麼? – mattytommo

+0

也許你的控制器方法沒有返回'JsonResult'? –

+0

@ jesus.tesh剛剛更新了我的OP,試着返回一個JsonResult,但得到一個錯誤「Value can not be null。Parameter name:controllerContext」。 。 。我沒有任何東西叫controllerContext,所以這是一個系統錯誤。 – adam

回答

5

你請求HTML不是JSON,所以它的返回值轉換爲字符串,而不是JSONifying它的。將您的dataType更改爲json

編輯

我假設你從ApiControllerController獲得。根據你的評論,情況可能並非如此。根據您是在開發一個API還是僅僅添加一個將JSON返回給標準控制器的操作,我推薦的是不同的。如果你正在開發一個API,那麼你應該從ApiController得到,然後內容類型將決定結果的格式。如果您只是使用返回JSON的方法來擴展標準控制器,那麼您將希望返回一個JsonResult。在後一種情況下,您需要同時請求json並將您的操作更新爲:

[HttpGet] 
public JsonResult GetTasks() 
{ 
    //Create an array to hold all of the task objects 
    var tasks = new List<Task> { }; 

    //Execute the select statement and get back a SqlDataReader object 
    DataTable table = DataAccess.ExecuteSelect("select Id, Name, Description, Starting, Ending from Tasks"); 

    foreach (DataRow dr in table.Rows) 
    { 
     //Assign values to the task object 
     Task task = new Task((int)dr["Id"], 
          (string)dr["Name"], 
          (string)dr["Description"], 
          (DateTime)dr["Starting"], 
          (DateTime)dr["Ending"]); 

     //Add task object to list of task objects 
     tasks.Add(task); 
    } 

    return Json(tasks, JsonRequestBehavior.AllowGet); 
} 
+0

當我嘗試時,它會出現錯誤:ajax例程。但request.status是200,並且request.statusText是「OK」 – adam

+0

@adam - 我已根據您的評論添加更多信息 – tvanfosson

+0

對不起,發送的信息不夠詳細。仍然有問題,但相當更新OP。 – adam