在 C# .NET 3.5 中使用 HTTPHandler 和 jQuery 周日历

发布于 2024-09-24 18:28:22 字数 1112 浏览 2 评论 0原文

几周来我一直在努力让它发挥作用,但都无济于事。我确信我的代码一定是因为一些相当小和愚蠢的事情而失败了,但是在尝试了多种不同的方法之后,我开始真正努力弄清楚问题可能是什么。有其他人设法获得 jQuery 周日历 (http://github.com/themouette/jquery -week-calendar) 使用返回 JSON 的 HTTPHandler ?

我尝试过: 对

  1. JSON 进行硬编码,使其作为字符串从处理程序中出来(例如“events: [{ etc }]”)
  2. 尝试使用或不使用初始“​​events :”
  3. 使用 LINQ 检索数据,然后使用序列化JavaScriptSerializer
  4. 使用 DataContractJsonSerializer 代替 使用
  5. 上述方法创建 ToJSON 方法
  6. 使用 $.getJson 检索数据
  7. 使用 $.get 代替
  8. 使用 $.ajax,使用“async = false”
  9. 将数据调用放入函数中,然后通过以下方式调用该函数:
    data: function(start, end, callback) {
        callback(getData());
    }

None其中似乎有效。我什至尝试使用 $.get、$getJSON 和 $.ajax 在日历代码之前运行数据调用,例如:

    $.getJSON('/content/handlers/GetScheduledAppointments.ashx', function(json) {
        $calendar.weekCalendar({
            .
            .
            .
            data: json
        });
    });

我尝试了很多不同的方法,我无法真正发布每个失败的代码示例,但是如果有人可以帮助我,我将非常乐意在需要时发布一些示例。

有没有人设法让这两件事一起工作......?

I've been trying to get this to work for weeks now, all to no avail. I am sure that my code must be failing through something fairly small and stupid, but having tried a number of different approaches I'm starting to really struggle as to what the problem might be. Has anybody else managed to get the jQuery Week Calendar (http://github.com/themouette/jquery-week-calendar) working with an HTTPHandler returning the JSON?

I've tried:

  1. Hard-coding the JSON to come out of the handler as a string (e.g. "events: [{ etc }]")
  2. Trying with or without the initial "events : "
  3. Using LINQ to retrieve data, then serializing with JavaScriptSerializer
  4. Using DataContractJsonSerializer instead
  5. Creating a ToJSON method with the above
  6. Using $.getJson to retrieve the data
  7. Using $.get instead
  8. Using $.ajax, with "async = false"
  9. Putting the data call in a function, then calling the function by:
    data: function(start, end, callback) {
        callback(getData());
    }

None of which seem to work. I've even tried running the data call before the calendar code using $.get, $getJSON and $.ajax, like:

    $.getJSON('/content/handlers/GetScheduledAppointments.ashx', function(json) {
        $calendar.weekCalendar({
            .
            .
            .
            data: json
        });
    });

I've tried so many different ways that I can't really post every example of code that fails, but if anybody can help me I'll be more than happy to post some examples if needed.

Has anybody managed to get these two things to work together...?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

歌入人心 2024-10-01 18:28:22

对于与我有同样问题的其他人,我有一些可能对您有所帮助的建议。这些只是我发现对我有帮助的事情,并且只是对那些浪费了数周宝贵时间思考为什么看似很好的代码不起作用的人的指导。我很清楚我的技能很弱(老头),但如果它能帮助拯救一个人一些时间,那么我的时间还没有完全浪费。

这适用于 C# .NET 3.5 Web 窗体,而不是 MVC。

首先,确保 Response 对象的 ContentType 和 ContentEncoding 属性设置为 JSON。过去我使用过“text/plain”,但这一次似乎对我不起作用:

context.Response.ContentType = "application/json";
context.Response.ContentEncoding = Encoding.UTF8;

如果使用 LINQ,按照日历期望的顺序和格式创建一个新对象将有助于最大限度地减少数据不规则问题。如果您需要只读约会,则只需将该选项添加到列表中即可。下面的“title”元素在 SQL 中充当 ISNULL 或 COALESCE 的作用,以防止返回 null:

var apps = (
    from a in db.Appointments
    select new {
        id = a.id,
        start = a.startTime.Value,
        end = a.endTime.Value,
        title = a.subjectLine == null ? "" : a.subjectLine
    }).ToList();

虽然有很多方法可以将数据集序列化为 JSON,但我发现最干净的方法是使用 NewtonSoft Json.NET 库。这就像添加一行来创建一个 JSON 对象一样简单,并具有必要的 ISO8601 日期格式:

return JsonConvert.SerializeObject(apps, new IsoDateTimeConverter());

就 jQuery 方面而言,我将只显示“data:”函数,因为这是让我感到困惑的部分最长:

data: function(start, end, callback) {
    $.ajax({
        url:        "/content/handlers/GetScheduledAppointments.ashx",
        type:       "GET",
        success:    function(json) {
            callback(json);
        },
        async:      false
    });
}

关于日期的一个方便的提示,这是我在开始使用 Json.NET 库之前遇到的 - 如果您根本无法让 .NET 以 jWC 喜欢的格式返回日期,那么使用 [Date.js 库来执行jQuery 本身的附加格式。几天来,无论我尝试什么,我都无法让后端以可在日历上呈现的格式输出开始和结束时间。在所有功能示例中(在 jQuery 中生成本地数据),日期都是使用以下格式创建的:

new Date(year, month, day, hour, minute)

因此,使用此基础,还可以显式转换从后端返回的日期,如 Date.js库几乎可以接受任何接近日期的内容并发挥其魔力:

data: function(start, end, callback) {
    $.ajax({
        url:        "/content/handlers/GetScheduledAppointments.ashx",
        type:       "GET",
        success:    function(json) {
            if ($.isArray(json)) { 
                $.each(json, function(key, value) { 
                    value.start = new Date(value.start); 
                    value.end = new Date(value.end); 
                });
            }
            callback(json);
        },
        async:      false
    });
}

我知道这些都不是很方便(甚至是优化),但希望这对那些在 jWC 和 .NET 方面遇到真正困难的人有用。

For anybody else having the same issues as me, I have a number of pointers that may help you. These are only things that I found helped me and are just guidance for anybody else who has wasted weeks of valuable time wondering why seemingly fine code doesn't work. I am well aware my skillz are weak (old man), but if it helps save even one person some time then my time hasn't been completely wasted.

This is for C# .NET 3.5 Web Forms, not MVC.

Firstly, make sure the ContentType and ContentEncoding properties of the Response object are set to JSON. In the past I have used "text/plain", but this doesn't seem to work for me on this occasion:

context.Response.ContentType = "application/json";
context.Response.ContentEncoding = Encoding.UTF8;

If using LINQ, creating a new object in the order and format the calendar is expecting will help minimise problems with data irregularities. If you require read-only appointments then you can just add the option to the list. The "title" element below is working as an ISNULL or COALESCE would in SQL, as to prevent nulls being returned:

var apps = (
    from a in db.Appointments
    select new {
        id = a.id,
        start = a.startTime.Value,
        end = a.endTime.Value,
        title = a.subjectLine == null ? "" : a.subjectLine
    }).ToList();

Whilst there are many ways of serializing the dataset into JSON, I have found the most clean method is to use the NewtonSoft Json.NET library. This is as simple as adding one line to create a JSON object, with the necessary ISO8601 date formatting:

return JsonConvert.SerializeObject(apps, new IsoDateTimeConverter());

As far as the jQuery side goes I'll only show the "data: " function, as this is the part that had me flummoxed for the longest:

data: function(start, end, callback) {
    $.ajax({
        url:        "/content/handlers/GetScheduledAppointments.ashx",
        type:       "GET",
        success:    function(json) {
            callback(json);
        },
        async:      false
    });
}

A handy tip regarding dates, which I came to before I started using the Json.NET library - if you simply cannot get .NET to return dates in a format that jWC likes, then use the[Date.js library to perform additional formatting in the jQuery itself. For days I couldn't get my back-end to output the start and end times in a format that would render on the calendar, no matter what I tried. In all the functioning examples (with local data being generated in the jQuery) the dates were being created using the following format:

new Date(year, month, day, hour, minute)

So, using this basis, it is also possible to explicitly cast dates returned from the back end, as the Date.js library will take almost anything approaching a date and work its magic:

data: function(start, end, callback) {
    $.ajax({
        url:        "/content/handlers/GetScheduledAppointments.ashx",
        type:       "GET",
        success:    function(json) {
            if ($.isArray(json)) { 
                $.each(json, function(key, value) { 
                    value.start = new Date(value.start); 
                    value.end = new Date(value.end); 
                });
            }
            callback(json);
        },
        async:      false
    });
}

I know none of this is very leet (or even optimised), but hopefully this can be of use to some people who are having real difficulty with jWC and .NET.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文