1

在我的控制器中,我有以下方法......非常简单。

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);
    }
4

1 回答 1

5

您请求的是 HTML 而不是 JSON,因此它将返回值转换为字符串而不是 JSON 化它。将您的更改dataTypejson.

编辑

我假设你是从ApiControllernot派生的Controller。根据您的评论,情况可能并非如此。根据您是在开发 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);
}
于 2013-06-05T14:04:50.773 回答