动态返回类型不工作,但jsonresult返回类型工作 [英] Dynamic return type not working but jsonresult return type working

查看:139
本文介绍了动态返回类型不工作,但jsonresult返回类型工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我碰到了,我不知道如何解决问题。
我有一个简单的控制器,其返回类型是动态的,但它不工作。

I am ran into a problem which i dont know how to resolve. I have a simple controller whose return type is Dynamic but its not working.

  public dynamic GetPosts()
    {
        var ret = (from post in db.Posts.ToList()
                   orderby post.PostedDate descending
                   select new
                   {
                       Message = post.Message,
                       PostedBy = post.PostedBy,
                       PostedByName = post.ApplicationUser.UserName,
                       PostedByAvatar = _GenerateAvatarUrlForUser(post.PostedBy),
                       PostedDate = post.PostedDate,
                       PostId = post.PostId,
                     }).AsEnumerable();
                   return ret;
    }

如果我改变了这个充满活力的返回类型JsonResult并替换返回RET返回JSON(RET,JsonRequestBehavior.AllowGet);它会工作。
我使用则Web API控制器之前,它是做工精细和动态的返回类型,但不知怎的,我面临着一些问题,所以我决定用正常的控制器。
我有他们的工作是动态追加后和到视图page.it的这样的事情发表评论淘汰赛视图模型---

If I changed this dynamic return type to JsonResult and replaces return ret to return Json(ret, JsonRequestBehavior.AllowGet); it will work. Before i was using web api controller then it was working fine with dynamic return type but somehow i was facing some problems so i decided to use normal controller. I have a knockout view model whose work is to dynamically append post and comment onto view page.it's something like this---

   function viewModel() {
    var self = this;
    self.posts = ko.observableArray();
    self.newMessage = ko.observable();
    self.error = ko.observable();
    self.loadPosts = function () {
        // to load existing posts
        $.ajax({
            url: postApiUrl1,
            datatype: "json",
            contentType: "application/json",
            cache: false,
            type: 'Get'
        })
        .done(function (data) {
            var mappedPosts = $.map(data, function (item) { return new Post(item); });
            self.posts(mappedPosts);
        })
        .fail(function () {
            error('unable to load posts');
        });
    }

self.addPost = function () {
    var post = new Post();
    post.Message(self.newMessage());
    return $.ajax({
        url: postApiUrl,
        dataType: "json",
        contentType: "application/json",
        cache: false,
        type: 'POST',
        data: ko.toJSON(post)
    })
   .done(function (result) {
       self.posts.splice(0, 0, new Post(result));
       self.newMessage('');
   })
   .fail(function () {
       error('unable to add post');
   });
}
self.loadPosts();
return self;
};

onButton点击,后期和注释正确保存在数据库中,但不能动态追加到视图页面。
我在这里上传错误的形象-----

我不知道什么是missing.what此错误消息指向。如何解决呢?如果任何code缺少那么请告诉我,我会上传过

I don't know what is missing.what this error message is pointing to. how to resolve it?If any code is missing then please tell me i will upload that too

推荐答案

默认情况下,一个Web API控制器能够返回序列化为XML或JSON数据,这取决于请求头。所以,当你使用的API控制器,​​该数据被返回到客户端以正确的格式。

By default, a Web API controller is able to return the data serialized as XML or JSON, depending on the request headers. So, when you used the API controller, the data was returned to the client in the correct format.

在一个MVC控制器的情况下,你可以返回某种的ActionResult ,这将发送一个predictable格式的响应。如果返回其他任何对象,你真的在​​如何将其格式化没有直接的控制权。例如返回一个字符串,返回原始字符串。但目前还不清楚如果返回任何其他对象是什么将被退回。我认为,在默认情况下,它确实的toString()

In the case of an MVC controller, you can return some kind of ActionResult, which will send a response in a predictable format. If you return any other object, you really have no direct control on how it will be formatted. For example returning an string returns a raw string. But it's not clear what will be returned if you return any other object. I think, by default, it does a toString().

更新: 我刚刚cheked什么是响应返回dynamc对象时,它是一个的text / html 响应与动态对象转换成字符串的例如,使用这个动作:

UPDATE: I've just cheked what is the response when returning a dynamc objects, and it's a text/html response, with the dynamic object converted to string For example, with this action:

    // GET Mailing/ArticuloVagon/dynamic
    [HttpGet]
    public dynamic Dynamic()
    {
        var r = new
        {
            a = 23,
            b = "kk",
            c = new List<string> {"x", "y", "z"}
        };
        return r;
    }

您得到这个答复:

Header: 
Content-Type:text/html; charset=utf-8

Content:
{ a = 23, b = kk, c = System.Collections.Generic.List`1[System.String] }

那么,一个有用的一种信息返回给你的客户,你需要指定它。要返回JSON最简单的方法是返回 JsonActionResult ,也可以手动创建响应。

So, to return an useful kind of information to your client you need to specify it. To return JSON the easiest way is to return JsonActionResult, or create a response manually.

正如你在你自己的问题说,有使用 JsonActionResult 没有问题。我建议你​​使用它。

As you say in your own question, there is no problem with using JsonActionResult. I'd recommend you using it.

不过,这将是更好的解决问题的路由怎么一回事,因为使用Web API控制器是非常容易和Web API控制器更轻。也许你应该打开一个新的问题是什么展示与路由的问题。我敢肯定,他们真的很容易解决。我使用这两种类型的控制器的许多项目。

However, it would be much better to solve the problems with routing beacuse using Web API controllers is much easier, and Web API controllers are lighter. Perhaps you should open a new question showing what are the problems with routing. I'm sure they're really easy to solve. I have many projects using both type of controllers.

这篇关于动态返回类型不工作,但jsonresult返回类型工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆