WCF 响应作为 ASP.NET WebForms 中的 Json,使用 Json.NET

发布于 2024-12-29 21:28:38 字数 1902 浏览 1 评论 0原文

我正在使用 WCF 服务,我想在其中响应对象列表。由于我的对象是由实体框架生成的,因此我无法真正返回列表,因为它有一些循环引用并且默认序列化失败。因此,我使用匿名类型来创建仅包含我需要的属性的对象列表。 这就是我正在做的事情,使用 Json.NET:

[OperationContract]
        public string DoWork()
        {
            using (X ent = new X())
            {
                var modules = from p in ent.Modules select new { Name = p.Name, Value = p.ID };
                return JsonConvert.SerializeObject(modules);
            } 
        }

现在这是我的 javascript,它在表中呈现结果:

function btn_onclick() {
            var srv = new DDSProjectManagement.ProjectsService();
            srv.DoWork(Res, null, null);
        }
        function Res(dataList) {
            var divObj = document.getElementById('tablePos');

            var name = 'Name';
            var desc = 'Description';

            var tableStart = '<table><tbody><tr><th>Name</th><th>Description</th></tr>';
            var tableContent = '';
            var tableEnd = '</tbody></table>';

            for (var i = 0; i < dataList.length; i++) {
                tableContent += '<tr><td>' + dataList[i].Name + '</td><td>' + dataList[i].Value + '</td></tr>';
            }
            divObj.innerHTML = tableStart + tableContent + tableEnd;
        }

如果我这样做,javascript 获取的参数只是一个字符串,并且无法将其视为列表我的对象。当然,它应该是一个 Json 字符串,我可以尝试解析它,以便从中提取对象。但我真的想像现在一样使用 javascript 并修改服务。例如,按以下方式更改我的服务就可以正常工作:

public List<SimpleObject> DoWork()
        {                
            return new List<SimpleObject>() { new SimpleObject("Florin", 1), new SimpleObject("Andrei", 2) };
        }

SimpleObject 不是 EntityFramework 对象,因此这没有问题。我想默认的序列化器是一个 Json 序列化器,并且 javascript 应该获得基本相同的参数:一个 Json 字符串。

所以我的问题是,当通过 Json.NET 构建字符串不起作用时,如何让我的方法将匿名类型对象列表发送到我的 JS? 提前致谢。

I'm using a WCF Service in which I would like to respond with a list of objects. As my objects are generated by entity framework, I can't really return a List as it has some circular references and default serialization fails. Thus, I'm using anonymous types to create a list of objects containing only the properties I need.
This is what I'm doing, using Json.NET:

[OperationContract]
        public string DoWork()
        {
            using (X ent = new X())
            {
                var modules = from p in ent.Modules select new { Name = p.Name, Value = p.ID };
                return JsonConvert.SerializeObject(modules);
            } 
        }

Now this is my javascript which renders the result inside a table:

function btn_onclick() {
            var srv = new DDSProjectManagement.ProjectsService();
            srv.DoWork(Res, null, null);
        }
        function Res(dataList) {
            var divObj = document.getElementById('tablePos');

            var name = 'Name';
            var desc = 'Description';

            var tableStart = '<table><tbody><tr><th>Name</th><th>Description</th></tr>';
            var tableContent = '';
            var tableEnd = '</tbody></table>';

            for (var i = 0; i < dataList.length; i++) {
                tableContent += '<tr><td>' + dataList[i].Name + '</td><td>' + dataList[i].Value + '</td></tr>';
            }
            divObj.innerHTML = tableStart + tableContent + tableEnd;
        }

If I do this, the parameter javascript gets is just a string and it is not able to see it as a list of my objects. Of course, it should be a Json string and I could try to parse it such that it extracts the objects from it. But I really want to use the javascript as it is now and modify the service. For example, changing my service in the following will work just fine:

public List<SimpleObject> DoWork()
        {                
            return new List<SimpleObject>() { new SimpleObject("Florin", 1), new SimpleObject("Andrei", 2) };
        }

SimpleObject is not an EntityFramework object so this has no problem. I suppose the default serializer is a Json one and javascript should get basically the same parameter: a Json string.

So my question is how do i make my method send a list of anonymous type objects to my JS as building the string via Json.NET didn't work?
Thanks in advance.

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

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

发布评论

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

评论(2

烟酉 2025-01-05 21:28:38

查看 SignalR ...它可以让您从服务器端将信息推送到 JavaScript。我做了类似的事情,我的 ASP.NET MVC3 页面上有一个 WCF 服务,然后每当我的服务接收到数据时,我就把它推送到我的 JavaScript 中。

我的服务将信息发送到我的 SignalR“中介”:

public void Message(string messagePacket)
    {
        new NotificationMediator().NotifyClients(messagePacket);
    }

在我的例子中,我只是新建一个新的中介(SignalR Hub),然后调用它的方法。这是我的 SignalR 处理程序 (NotifyClients):

public void NotifyClients(string message)
    {
        Hub.GetClients<NotificationMediator>().Log(message);

    }

现在 Log 是我的 UI 上的 JavaScript 方法。这是我的 JavaScript 代码来处理这个问题:

mediator.Log = function (message) {
        var msg = $.parseJSON(message);
        $("#logContainer").append(msg.Data + "<br />");

Look into SignalR ... It will let you push information to your JavaScript from your server side. I do something similar where I have a WCF service on my ASP.NET MVC3 page and then whenever my service receives data I just push it to my JavaScript.

My service sending info to my SignalR 'mediator':

public void Message(string messagePacket)
    {
        new NotificationMediator().NotifyClients(messagePacket);
    }

In my case I just new up a new mediator (SignalR Hub) and then call a method on it. Here is my SignalR handler for this (NotifyClients):

public void NotifyClients(string message)
    {
        Hub.GetClients<NotificationMediator>().Log(message);

    }

Now that Log is a JavaScript method on my UI. Here is my JavaScript code to handle this:

mediator.Log = function (message) {
        var msg = $.parseJSON(message);
        $("#logContainer").append(msg.Data + "<br />");
窝囊感情。 2025-01-05 21:28:38

这终于对我有用了。该方法的返回类型是 Stream,其工作原理如下:

    public Stream GetModules()
            {
                using (PMEntity ent = new PMEntity())
                {                
                    List<Module> ret = new List<Module>();
                    ret = ent.Modules.Include("Project").ToList();

                    return new MemoryStream(
                            Encoding.UTF8.GetBytes(
                            JsonConvert.SerializeObject(
                            ret.Select(e => new { Name = e.Name, Value = e.ID }))));
                }
            }

This finally worked for me. The return type of the method is Stream and here is how it works:

    public Stream GetModules()
            {
                using (PMEntity ent = new PMEntity())
                {                
                    List<Module> ret = new List<Module>();
                    ret = ent.Modules.Include("Project").ToList();

                    return new MemoryStream(
                            Encoding.UTF8.GetBytes(
                            JsonConvert.SerializeObject(
                            ret.Select(e => new { Name = e.Name, Value = e.ID }))));
                }
            }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文