【问题标题】:ASP.NET MVC Problem sending class objects to JS - empty objects in JS arrayASP.NET MVC 向 JS 发送类对象的问题 - JS 数组中的空对象
【发布时间】:2021-10-14 19:55:15
【问题描述】:

我们有一个带有控制器的 ASP:NET MVC 应用程序。我们 HTTP GET 到控制器中的一种方法。 在其中,我们要创建 Event 对象并将列表及其所有属性发送回客户端(在 JS 中)。

它不起作用,因为在 JS 中我们会收到一个空对象列表。请参阅随附的屏幕截图。我们缺少什么?

提前感谢您的帮助。

ASP.NET MVC 控制器:

public class KalenderController : Controller
{
    public class Event
    {
        public Event(int _id, string _title)
        {
            id = _id;
            title = _title;
        }

        public int id;
        public string title;
    }

    [HttpGet]
    public JsonResult GetEvents()
    {
        StringValues start = "";
        Request.Query.TryGetValue("start", out start);
        StringValues end = "";
        Request.Query.TryGetValue("end", out end);

        DateTime dtStart = DateTime.Parse(start.ToString().Replace(" ", "+"));
        DateTime dtEnd = DateTime.Parse(end.ToString().Replace(" ", "+"));

        List<Event> events = new List<Event>();

        DateTime dt = dtStart;
        while(dt <= dtEnd)
        {
            events.Add(new Event(1, "title"));

            dt = dt.AddDays(1);
        }

        return Json(events);
    }
}

JS代码:

$.ajax({
    url: "Kalender/GetEvents?start=" + fetchInfo.startStr + "&end=" + fetchInfo.endStr,
    type: 'GET',
    success: function (data) {
        console.dir(data);
        console.log(data.d);
    },
    error: function (jqXHR, textStatus, errorThrown) {
        alert("Fehler beim Abrufen des Skripts: " + textStatus + " - " + errorThrown);
    },
    failure: function (bool) {
        alert("Fehler beim Abrufen des Skripts");
    }
});

向客户端发送数据的结果: JS数组中的空对象:https://i.stack.imgur.com/Zi7v7.png

【问题讨论】:

  • 在 Parse() 语句之后在控制器中设置断点。 dtStart 是正确的值还是 0(默认值,因为它是一个结构)?如果您知道日期字符串的格式,我更喜欢 ParseExact (docs.microsoft.com/en-us/dotnet/api/…)。顺便提一句。您可以使用 [FromQuery] 作为 GetEvents 的参数来获取您的查询参数。
  • 日期时间已经正确,但感谢您提出 [FromQuery] 属性!

标签: javascript c# asp.net asp.net-mvc


【解决方案1】:

您应该将公共字段更改为 Event 对象的公共属性

public class Event
{
    public Event(int _id, string _title)
    {
        Id = _id;
        Title = _title;
    }

    public int Id { get; set; }
    public string Title { get; set; }
}

【讨论】:

    猜你喜欢
    • 2020-04-17
    • 2015-05-31
    • 2019-05-04
    • 2020-03-14
    • 2020-10-11
    • 1970-01-01
    • 2015-06-19
    • 2015-11-21
    • 1970-01-01
    相关资源
    最近更新 更多