简体   繁体   English

C#MVC4-将自定义类的列表传递回Javascript

[英]C# MVC4 - pass List of custom class back to Javascript

In my controller, I have the following method.. pretty straight forward. 在我的控制器中,我有以下方法..非常简单。

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

    }
}

Which creates an object of type Task. 这将创建一个Task类型的对象。 Class shown here 班级在这里显示

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

I have an Ajax call to that method. 我对该方法有一个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
    }

});

The output from the two console.dir() lines: 来自两个console.dir()行的输出:

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

How do I get back a Javascript object where I can loop through each "Task" in the array... to output the "Id", "Name" (etc) as desired? 如何获取一个Javascript对象,可以在其中循环遍历数组中的每个“任务” ...以根据需要输出“ Id”,“ Name”(等)?

I've tried various combinations in C# to convert my List of Tasks with no success 我尝试了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);
    }

You're requesting HTML not JSON so it's converting the return value to a string instead of JSONifying it. 您要的是HTML,而不是JSON,因此它会将返回值转换为字符串,而不是JSON化它。 Change your dataType to json . 将您的dataType更改为json

Edit 编辑

I'm assuming that you're deriving from ApiController not Controller . 我假设您是从ApiController而不是Controller派生的。 Based on your comment, that may not be the case. 根据您的评论,事实并非如此。 Depending on whether you're developing an API or just adding an action that returns JSON to a standard controller, what I'd recommend is different. 根据您是开发API还是仅添加将JSON返回到标准控制器的操作,我建议的方法有所不同。 If you're developing an API, then you should derive from ApiController and then the content type will determine the format of the result. 如果要开发API,则应从ApiController派生,然后内容类型将确定结果的格式。 If you're just extending a standard controller with a method that returns JSON, then you'll want to return a JsonResult. 如果您只是使用返回JSON的方法扩展标准控制器,则需要返回JsonResult。 In the latter case you'll need to both request json and update your action to: 在后一种情况下,您需要同时请求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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM