且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

动态返回类型不工作但jsonresult返回类型工作

更新时间:2023-02-15 12:21:13

默认情况下,一个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.