Reputation:
All,
I have the following code:
$.ajax({
url: '@Url.Action("GetMerchantUsers", "Merchant")',
dataType: 'json',
success: function (json) {
var mappedTasks = $.map(JSON.parse(json), function (item) { return new Task(item) });
self.tasks(mappedTasks);
}
});
This calls an MVC controller that returns a list of objects from a JsonResult method. It works totally fine. However, I need to rewrite this method because there will never be more than one Task being returned from the server. When I return one task from the server, however, the .NET JsonResult method doesn't put '[' and ']' at the beginning and end of the json, so $.map() sees the PROPERTIES of the object as a collection, but I just want to map one object returned from the server to a task observable instead of multiple tasks to a tasks observable. I'm new to knockout...how do I map a single Json object, like i'm doing above for a collection. I'll be happy to provide more info if needed!
Also, I've already mapped the object to a generic JavaScript type, but I want to map it to my Task type specifically.
Upvotes: 0
Views: 56
Reputation: 1360
Since you're no longer processing a list, you don't need $.map()
(since it just loops through and applies a function to every item in a list), you can just pass the parsed JSON reponse to your Task
constructor...like so perhaps:
var mappedTasks = new Task(JSON.parse(json));
If your self.tasks()
method expects a list, you can just wrap it:
self.tasks([mappedTasks]);
Upvotes: 2