问题
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
回答1:
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.
来源:https://stackoverflow.com/questions/33623147/dynamic-return-type-not-working-but-jsonresult-return-type-working