简体   繁体   中英

ASP.NET MVC Returning JSON Objects of ViewModels

It seems recently that all I ever seem to post about is ASP.NET MVC with JSON - you would think I'd learn by now! However, strange things keep happening that I can't explain!

I have a Controller method that returns a JsonResult:

public JsonResult GetAllUserTasksForStage(int StageID, string Username)
{
    var uM = ManagerProvider.GetUserManager();
    var tM = ManagerProvider.GetTaskManager();
    var tasks = tM.GetAllUserTasks(StageID, uM.GetUser(Username).ID);
    // GetAllUserTasks returns IEnumerable<TaskViewModel>
    // Encode this into Json and return it
    return Json(tasks, JsonRequestBehavior.AllowGet);
}

This method completes successfully, however when it comes to receiving this on my View, problems arise. I have tried using both $.post(...) and $.getJSON(...) - for the $.post() I removed the JsonRequestBehavior from the Controller method.

Reading the jQuery documentation I have seen that the callback functions on both $.post and $.getJSON only fire if the result is valid JSON - which leads me to believe that something is wrong with the returned result of GetAllUserTasksForStage.

The TaskViewModel class is defined as:

public class TaskViewModel
{
    public int ID { get; set; }
    public UserViewModel Assignee { get; set; }
    public DateTime Created { get; set; }
    public UserViewModel Creator { get; set; }
    public DateTime Due { get; set; }
    public string TaskDescription { get; set; }
    public string TaskTitle { get; set; }
    public bool Completed { get; set; }
    public StageViewModel Stage { get; set; }
    public IEnumerable<TaskAuditViewModel> TaskAudits { get; set; }
}

It's completely stumped me, as I've used $.post and $.getJSON on the same View several times with no problems - but never returning TaskViewModel.

Any ideas?

Thanks,

Chris

I would recommend breaking the problem down a bit. There are too many things going on. First try returning a simple JSON object. This will allow you to ensure the JavaScript / transport is correct. Then try to slowly introduce your object as the return type. This way you can determine for yourself where the JSON is invalid.

Try calling your Json method directly from the browser URL (skipping the jQuery part) and see what you get. I am guessing that you probably have something like a jQuery ajax call into that action. So try calling it directly. This usually will reveal the plain error message.

Your model is complex (it contains other models inside it).

I don't have the facts, but it seems that the Json function in MVC has problems passing complex models to the JQuery part. If you inspect the result on the mvc action (F9 on the line where Json is), you can see the Json maps the complex Model by parts like: base, Model1, Mode2,...

When this is the situation, the Json returns a mapped result, but somehow the clinet jQuery part cannot understand it, there is not error, but data cannot be consumed on the client.

I have tried myself to find a solution but haven't found one yet. I tried several combinations like you (.post, .get, .ajax... JsonResult, etc etc.). Unfortunatelly, only way seems to work is returning (from the action) a manually created Json result like this:

[HttpPost]
        public ActionResult GetOrderDetail(int id)
        {
            var orderDetail = orderService.GetOrderDetail(id);

            var result = Json(new
            {
                ItemDescription = orderDetail.ItemDescription,
                ItemUrl = orderDetail.ItemUrl
            });

            return result;
        }

In this case, my model OrderDetail has two other models inside: Order, OrderMessages, and has same problem as you describe. By mapping manually property to property like shown here, it works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM