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

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

问题描述

我遇到了一个我不知道如何解决的问题。
我有一个简单的控制器,其返回类型为Dynamic,但不起作用。

  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),
发布日期= post.PostedDate,
PostId = post.PostId,
})。AsEnumerable();
return ret;
}

如果我将此动态返回类型更改为JsonResult并替换return ret返回Json(ret,JsonRequestBehavior.AllowGet);它将工作。
在我使用web api控制器之前,它的工作正常与动态返回类型,但不知何故我面临一些问题,所以我决定使用普通控制器。
我有一个淘汰视图模型,其工作是动态地附加发布和评论到view page.it这样的东西---

  function viewModel(){
var self = this;
self.posts = ko.observableArray();
self.newMessage = ko.observable();
self.error = ko.observable();
self.loadPosts = function(){
//加载现有帖子
$ .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 ){
错误('无法加载帖子);
});
}

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 );
});
}
self.loadPosts();
返回自我;
};

onButton点击,发布和注释已正确保存在数据库中,但未动态附加到视图页面。
i我上传错误图像-----



我不知道什么是丢失。这个错误消息指向哪里。如何解决?如果有任何代码丢失,请告诉我,我也会上传那个

解决方案

默认情况下,一个Web API控制器可以根据请求标头返回序列化为XML或JSON的数据。因此,当您使用API​​控制器时,数据以正确的格式返回给客户端。



对于MVC控制器,您可以返回某种 ActionResult ,它将以可预测的格式发送回复。如果您返回任何其他对象,您真的没有直接控制如何格式化。例如,返回一个字符串返回一个原始字符串。但是,如果您返回任何其他对象,将不会返回什么。我认为,默认情况下,它执行 toString()



更新: > text / html 响应,将动态对象转换为字符串例如,使用此操作:

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

您收到此回复:

 标题:
内容类型:text / html; charset = utf-8

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

所以,要向客户端返回一种有用的信息,您需要指定它。要返回JSON,最简单的方法是返回 JsonActionResult ,或手动创建一个响应。



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



然而,使用Web API控制器解决路由beacuse的问题会更好一些,Web API控制器打火机。也许你应该打开一个新问题,显示路由问题是什么。我相信他们真的很容易解决。我有很多项目使用两种类型的控制器。


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;
    }

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 click, post and comment are properly saved in the database but not dynamically appended to the view page. i am uploading image of error here-----

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

解决方案

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.

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().

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;
    }

You get this response:

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

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

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.

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

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天全站免登陆