views:

118

answers:

2

Hi all,

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

A: 

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.

rcravens
A: 

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.

Johannes Setiabudi