如何从VC Controller返回回调json?

时间:2014-08-22 06:21:30

标签: asp.net-mvc json asp.net-web-api

我在客户端使用第三方Kendo UI。它期望来自服务器的数据格式如下。

        callback([{"TaskID":4,"OwnerID":2,"Title":"Bowling}])

我在服务器端有以下代码

    public JsonResult GetAllAppointments()
    {
        IEnumerable<AppointmentModel> appointmentCollection = app_repository.GetAll();
        if (appointmentCollection == null)
        {
            return Json(appointmentCollection, JsonRequestBehavior.AllowGet);
        }
        return Json(appointmentCollection, JsonRequestBehavior.AllowGet);
    }

但这只返回json,如何添加&#34;回调&#34;对吗?

1 个答案:

答案 0 :(得分:0)

理想情况下,您应该在客户端获得一个拦截器,它可以让您修改您的响应格式。但由于您没有提供任何进一步的细节,我将无法对此发表评论。

您可以将JsonResult的返回类型更改为字符串并手动序列化您的响应。您可以使用Json.NET来序列化您的响应。

这是一个NuGet LINK

public class AppointmentModel
    {
        public string TaskID { get; set; }
        public string OwnerID { get; set; }
        public string Title { get; set; }
    }

    public string GetAllAppointments()
    {
        string responseFormat = @"callback({0})";

        IEnumerable<AppointmentModel> appointmentCollection = getDummyAppoitments();
        if (appointmentCollection != null)
        {
            string json_string = Newtonsoft.Json.JsonConvert.SerializeObject(appointmentCollection);

            return string.Format(responseFormat, json_string);;
        }

        //no items were present so sending empty response;
        return string.Format(responseFormat, "[]");;
    }

    private IEnumerable<AppointmentModel> getDummyAppoitments()
    {
        return new List<AppointmentModel>() { 
            new AppointmentModel()
            {
                TaskID = "4",
                OwnerID = "2",
                Title = "Bowling"
            }
        };
    }

查看回复。

enter image description here

干杯!!