code_junkie

Is there a Request.IsMvcAjaxRequest() equivalent for jQuery?

Nov 12th, 2011
43
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.43 KB | None | 0 0
  1. public static class HttpRequestBaseExtensions
  2. {
  3. public static bool IsjQueryAjaxRequest(this HttpRequestBase request)
  4. {
  5. if (request == null)
  6. throw new ArgumentNullException("request");
  7.  
  8. return request["__JQUERYASYNCPOST"] == "true";
  9. }
  10. }
  11.  
  12. if (Request.IsjQueryAjaxRequest())
  13. //some code here
  14.  
  15. $('form input[type=submit]').click(function(evt) {
  16. //intercept submit button and use AJAX instead
  17. evt.preventDefault();
  18.  
  19. $.ajax(
  20. {
  21. type: "POST",
  22. url: "<%= Url.Action("Create") %>",
  23. dataType: "json",
  24. data: { "__JQUERYASYNCPOST": "true" },
  25. success: function(data) {alert(':)');},
  26. error: function(res, textStatus, errorThrown) {alert(':(');}
  27. }
  28. );
  29. });
  30.  
  31. if (Request.Headers["X-Requested-With"] == "XMLHttpRequest")
  32. return Json(...);
  33. else
  34. return View();
  35.  
  36. post: function(url, data, callback, type) {
  37. var postIdentifier = {};
  38. if (jQuery.isFunction(data)) {
  39. callback = data;
  40. data = {};
  41. }
  42. else {
  43. postIdentifier = { __JQUERYASYNCPOST: true };
  44. jQuery.extend(data, postIdentifier);
  45. }
  46.  
  47. return jQuery.ajax({
  48. type: "POST",
  49. url: url,
  50. data: data,
  51. success: callback,
  52. dataType: type
  53. });
  54. }
Add Comment
Please, Sign In to add comment