开发者

Click for a button does not get bound correctly on first click, but is correctly bound on the second click

I am using VS2010, MVC3.

I have the following jQuery script to, upon clicking a button, have an ActionResult in the control开发者_C百科ler stream the PDF version of the page to a new window.

However, here is what happens:

When the page first is rendered I get the alerts: "in hereb1" and a correct url value for actionUrl.

The first time I click on the button, I get the alerts "in hereb2" and "undefined" as value for url, and a new window opens with error for undefined resource.

The third time I click on the button, I get the alerts "in hereb2" and the correct url value (same value as actionUrl), and a new window opens with expected result. No error.

Why the first click does not have access to the correct value of actionUrl?

<script type="text/javascript">
 $(document).ready(function () {
     alert("in hereb1");
     var actionUrl = '@MvcHtmlString.Create(Html.BuildUrlFromExpressionForAreas<MyController>(c => c.GeneratePdf(Request.Url.ToString())))';
     alert(actionUrl);
     $("#btnPdf").click(function () {
         var url = $(this).attr("href");
         $(this).attr("href", actionUrl);
         alert("in hereb2");
         alert(url);
         var win = window.open(url, "PdfVersion");
         win.focus();
         return false;
     });
  });
 </script>

Thanks


if you are trying to open actionUrl in a new tab/window the following code may help

$("#btnPdf").click(function () {
     //var url = $(this).attr("href");
     $(this).attr("href", actionUrl);
     alert("in hereb2");
     alert(actionUrl);
     var win = window.open(actionUrl, "PdfVersion");
     win.focus();
     return false;
 });

What your code does is that gets the url to which the btnPdf and opens the url in a new window/tab and sets the href attribute of the btnPdf to the actionUrl if you are trying to do this ensure that already serving page with the btnPdf's attribute href alredy set.


Switch

var url = $(this).attr("href");
$(this).attr("href", actionUrl);

to

$(this).attr("href", actionUrl);
var url = $(this).attr("href");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜