4

I have page in MVC2 that contain a grid and image button. When image button is clicked, the currentPage, orderBy and filter will be posted to a controller in JQuery. The code is,

<script type="text/javascript">
$("#ExportExcel").click(function (e) {
e.preventDefault();

var resourceId = $('#resourceId').val();
var grid = $('#Grid').data('tGrid');
var pagenum = grid.currentPage;
var orderBy = grid.orderBy
var filter = grid.filterBy;

$.ajax({
url: '@Url.Action("ExportToExcel", "ExportExcelButton")',
data: { resourceId: resourceId, pagenum: pagenum, orderBy: orderBy, filter: filter },
type: 'POST',
success: function (data) {
}
});
});
</script>

<a href="<%: Url.Action("ExportToExcel", "ExportExcelButton") %>"> <img src='<%: Url.Content("~/Content/Images/ExportExcelButton.gif") %>'/></a>

public ActionResult ExportToExcel(string resourceId, string pagenum, string orderBy, string filter)

However, when image button is clicked, all data are null in ExportToExcel action. I wonder what is the right way to do it. Thanks a lot.

  • Your code looks about alright. Have you tried extracting `data` to a variable and inspecting its value before posting? Have you debugged and inspected the value of `Request.Form` in your action? – David Hedlund Jul 18 '12 at 06:30
  • 1
    What is this `$("#ExportExcel")` that you're looking for? That listener should probably be registered on DOMReady, if it isn't. I can't see that the anchor has such an ID. Are you sure that the AJAX post is being submitted, and the link is not just followed to the action? – David Hedlund Jul 18 '12 at 06:32
  • I would suggest two things: 1) Check Firebug to see what's actually posting, and 2) Add the Glimpse (http://getglimpse.com/) NuGet package so that you can see how the action is processed on the server. – Tieson T. Jul 18 '12 at 06:55
  • Are any of those parameters an array? If yes then you could add 'traditional: true' to your ajax call – Tx3 Jul 18 '12 at 12:39

1 Answers1

0

i see two problems in your code:

  1. in the html you didn't specify the id of the link so clicking on it just navigated to the action, this is why you saw null in the parameters - none were sent
    it should be:

    <a id="ExportExcel" href="<%: Url.Action("ExportToExcel", "ExportExcelButton") %>"> <img src='<%: Url.Content("~/Content/Images/ExportExcelButton.gif") %>'/></a>
    
  2. put the script tag below the link deceleration or bind during the $(document).ready(..)

Avi Pinto
  • 4,266
  • 2
  • 24
  • 24
  • in your new solution, when you changed it to use the onclick, you lost the e.preventDefault(); so clicking on the link actually made navigation – Avi Pinto Jul 18 '12 at 19:42