0

I have a gallery of images on a webpage and a "Print" button which then calls the browser print using window.print().

<button class="button current" id="printButton" onClick="window.print()">
Print
</button>

I have also used some CSS using @@media print to specify the page size.

This works very nicely and I have found no good reason to make this more complicated. However, when the user has completed or cancelled the print, it returns to the page and seems to refresh the page without triggering the controller. This loses various setting that have been sent to the page via the controller using ViewBag and TempData.

I don't really understand what is refreshing the page without a call being made to the controller, neither HttpGet nor HttpPost pick this up. Any suggestions?

3
  • Perhaps the issue you are facing may have to do with the respect in the way the browser is handling the print function window. When the print dialog is closed (either through printing or through cancellation), sometimes the browser may simply refresh page. Commented Aug 31, 2024 at 18:39
  • You can try other method to persist your data even if there is a refresh on the page. 1. Use Session instead of ViewBag/TempData 2. Store the data inside cookies and retrieve back when the page refresh 3. Create a separate action that returns a view designed for printing. I hope this can be of help Commented Aug 31, 2024 at 18:47
  • What you mean viewdata missed? I found the viewdata will not missed even you use the print method. Commented Sep 2, 2024 at 7:02

1 Answer 1

0

it returns to the page and seems to refresh the page without triggering the controller. This loses various setting that have been sent to the page via the controller using ViewBag and TempData.

Firstly, if the page is refreshed/reloaded, the request would be made from browser side and reach to web server and controller action, then generate view result and send response to browser.

For more information about ASP.NET Core MVC Request Life Cycle, you could check this doc: https://www.c-sharpcorner.com/article/asp-net-core-mvc-request-life-cycle/

Besides, if you'd like to prevent page from reloading/refreshing after you click print button to keep original inputs/contents, you can try to modify the code like below.

<button class="button current" id="printButton" onClick="window.print();return false;">
    Print
</button>
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.