2

ASP.Net Web Application.

Is it possible to access a JavaScript function located on the master page from a C# class function?

Below is a description of what I'm attempting to do...

When user clicks save button, database procedure called that returns value indicating if it was successful. This value is fed into a C# function which is located in a C# class file. This function determines if the save was successful and has two paths:

Successful Path: Store "Save Successful" in session variable. Call JavaScript function that momentarily displays the message that is stored in the session variable.

Failure Path: Reverse all changes made with this transaction number. Store "Save was unsuccessful" in session variable. Call JavaScript function to display message that is stored in the session variable.

I'd like to use JavaScript to display the message since I have the ability to do it neatly and without requiring the user to click a button.

Thanks for your help! :)

G8Tech
  • 31
  • 7

3 Answers3

2

Use Ajax. Make a call with JavaScript to a ASP.Net PageMethod and have the return value be the string response ("Success"/"Failure"). Here's an article that will help you accomplish this:

Calling PageMethods With jQuery

Good luck!

Trevor
  • 13,085
  • 13
  • 76
  • 99
0

You can inject JavaScript.

http://msdn.microsoft.com/en-us/library/aa478975.aspx

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
  • Thanks for your response! The example uses RegisterStartupScript which has been depreciated and now considered obsolete. http://msdn.microsoft.com/en-us/library/system.web.ui.page.registerstartupscript.aspx Do you know what I could use in place of this code? – G8Tech Sep 23 '11 at 16:01
0

In general, no. I'm not saying that it is impossible, but this is not the normal way.

Let me explain. The C# code runs on the server, and is used to assemble the page and scripts to be delivered to the browser. The browser executes the javascript. (The browser contains a javascript runtime engine to accomplish this.)

You can call C# code from javascript, but only if the C# code is exposed via a web service. (Think [WebMethod]).

The server doesn't normally have a javascript runtime engine to use when creating a page.

I think for your case, the easiest path to a solution would be to display the message directly using the C# code.

Matt Brunell
  • 10,141
  • 3
  • 34
  • 46