Add

How To Call A JavaScript Method From C#

Introduction

This is very silly thing but used very often. Calling a JavaScript Method to do something from code behind(C#) is not so difficult.

You may need this thing in order to show a custom alert using jQuery modal pop up, or for custom redirection when you are in an IFrame.

Behind The Scene


Recently I was stuck in some redirection problems. The senario is something like, I was in some iframe but after session out I need to go back to the login page. But the control in not in my hand as I am inside an iframe.
I tried a lot of things but what resulted me is reloading or rendering the page I was referring inside the iframe. But my purpose was to redirect the whole page to login page.
So I did this using JavaScript, and I need to call a JavaScript function form the C# code when session is out.
There are some way in which you can call a JavaScript function from code behind.

  // redirect user to home page.
  ScriptManager.RegisterStartupScript(this, GetType(), "load", "closeDocumentIFrame();", true);
 
*closeDocumentIFrame(); is the method written in the aspx page
  // redirect user to home page.
  ClientScript.RegisterStartupScript(GetType(), "Load", String.Format("<script type='text/javascript'>closeDocumentIFrame();</script>"));
 
*closeDocumentIFrame(); is the method written in the aspx page
  // redirect user to home page.
  ClientScript.RegisterStartupScript(GetType(), "Load", String.Format("<script type='text/javascript'>window.parent.location.href ='{0}' </script>", "http://www.google.com"));
 
You can too add the JavaScript code here instead of writing another method in page level.

Happy Coding...

No comments:

Post a Comment