Call javascript from code behind

Posted on

Call javascript from code behind – Even if we have a good project plan and a logical concept, we will spend the majority of our time correcting errors abaout javascript and Furthermore, our application can run without obvious errors with JavaScript, we must use various ways to ensure that everything is operating properly. In general, there are two types of errors that you’ll encounter while doing something wrong in code: Syntax Errors and Logic Errors. To make bug fixing easier, every JavaScript error is captured with a full stack trace and the specific line of source code marked. To assist you in resolving the JavaScript error, look at the discuss below to fix problem about Call javascript from code behind.

Problem :

How can I call a javascript function from code behind?
The most popular response is “ScriptManager.RegisterStartupScript” however, that does not work in my situation.

I have a vb class that is doing a database check to see if a record exists. If exists, then call a javascript function to display an alert(“Record exists”)

So I am doing something like

Dim strMessage as string = "javascript:RecordExists('Param');"  

How do I call this function from my class?

Solution :

If DataStore.Record.Exists(theRecord) Then

    Dim script As String = "alert('Record exists')"
    If Not Page.ClientScript.IsStartUpScriptRegistered(Me.GetType(), "alertscript") Then
        Page.ClientScript.RegisterStartUpScript(Me.GetType(), "alertscript", script, True)

    End If
End If

you would do it like above, where you should replaceDataStore.Record.Exists(theRecord) with condition that checks database record exists

You need to think about your script in a slightly different way – remember, JavaScript runs client-side, and VB.NET runs server-side. So you can’t “call” JavaScript from the server side.

However, you can generate JavaScript on the server side, but it will need to be output to the page before it can run.

If you were doing a full page postback, a crude way of achieving it would be to assign the script or function to a Literal control, which renders its Text property on the HTML page exactly as written.

Then, your script will execute at the point the Literal is rendered.

A neater way of doing it is to add your script to the page via a ScriptManager as you noted. Rather than a StartupScript, you could try using .RegisterClientScriptBlock() instead? You don’t mention what it is about your situation that doesn’t work?

The most comprehensive way of doing it would be to use AJAX – either .NET’s built-in framework, or jQuery. jQuery’s AJAX (and AJAX in general) is a separate topic, which you can read about here.

Leave a Reply

Your email address will not be published. Required fields are marked *