JQuery to parse array of objects sent from Webmethod


/ Published in: C#
Save to your folder(s)



Copy this code and paste it in your HTML
  1. /// <summary>
  2. /// Return list of anonymous product highlight objects.
  3. /// </summary>
  4. /// <param name="productID"></param>
  5. /// <returns></returns>
  6. [WebMethod]
  7. public static List<object> GetHighlights(int productID)
  8. {
  9. FTJEntities context = new FTJEntities();
  10. return (from h in context.ProductHighlights where h.ProductID == productID select new { h.Description, h.DisplaySequence }).ToList<object>();
  11. }
  12.  
  13. //jquery to send request:
  14. $.ajax({
  15. type: "POST",
  16. url: "/Admin/Products/Overview.aspx/GetHighlightsf",
  17. data: "{productID: '" + $('#hfProductID').val() + "' }",
  18. contentType: "application/json; charset=utf-8",
  19. dataType: "json",
  20. success: function (msg) {
  21. if (msg.d == "false") alert('There was an error retrieving product highlights via ajax.');
  22. var highlights = msg.d;
  23. $.each(highlights, function (index, highlight) {
  24. RenderHighlight(highlight);
  25. });
  26. },
  27. failure: function (msg) {
  28. alert('Error: ' + msg);
  29. }
  30. });
  31.  
  32. //the function that renders the new table row:
  33. function RenderHighlight(highlight) {
  34. highlightRow = '<tr><td><input type="text" name="highlight" value="' + highlight.Description + '" class="text-input large-input"/></td><td class="tools"><a href="#" class="add">Add</a><a href="#" class="remove" rel="">Remove</a></td></tr>';
  35. $('#highlights tbody:last').append(highlightRow);
  36.  
  37. if ($('a.add').size() == 1) {
  38. $('a.remove').hide();
  39. }
  40. }

URL: http://www.mikesdotnetting.com/Article/96/Handling-JSON-Arrays-returned-from-ASP.NET-Web-Services-with-jQuery

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.