0

My Ajax block looks like so:

    $('#btnTest').click(function(){
      $.getJSON('/User/ViewMessages',function(result) {
            // TODO: update the DOM with the items
            $("table#tblMessages").append("<tr><td>"+result.MESSAGETEXT+"</td><td>"+result.DATESENT+"</td>");
      });
    });

My Action in my Controller looks like such:

        public ActionResult ViewMessages()
    {
        var recipient = Convert.ToInt32(HttpContext.Session["User_Id"]);
        var query = (from m in context.Messages
                     from rec in context.Recipients
                     where rec.RECIPIENT == recipient
                     where rec.MESSAGEID == m.MESSAGEID
                     select new 
                     {
                         m.MESSAGETEXT,
                         m.DATESENT
                     }).ToList();
        return Json(query.ToList());
    }

When Debugging, my query variable returns: { MESSAGETEXT = "seresr", DATESENT = {9/15/2011 11:06:45 AM} }

The thing is, my table is added with "undefined" for both my values. Where have i gone wrong? I have already added the maproute as well, but I'm still out of luck.

1 Answer 1

1

It looks like you're returning a list, which will be represented in JSON as an array. So your result object is a JavaScript array rather than a single object. To loop through all the items and add a table row for each, try something like this:

$.getJSON('/User/ViewMessages', function(result) {
    for (var i in result) {
        var row = result[i];
        $("table#tblMessages").append("<tr><td>" + row.MESSAGETEXT
            + "</td><td>" + row.DATESENT + "</td>");
    }
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.