0

Hello everyone! I am working on a school project and I need to give to a paragraph element some innerHTML from a table in my database and I tried doing it with some javascript but having the connection script in c# I am now in need to call the JavaScript from within said c# script. I tried using the following commands:

if(!myPage.ClientScript.IsStartupScriptRegistered("CallMyFunction"))
        myPage.ClientScript.RegisterStartupScript(myPage.GetType(), "CallMyFunction", "<script language='javascript'>TypeText(" + myPage + "," + text1 + "," + text2 + "," + text3 + ")</script>", false);

Where:

  • myPage is a Page variable that gets the name of the web page. This variable is properly taken as I used some commands like changing the page title, and it did work as intended.
  • text1, text2, text3 are three strings that get their values from the database table. Also verified if it works with some test commands.

The problem is that the command shown above doesn't work. I tried using alert('test') inside the TypeText() function that I have in the RegisterStartupScript. So I was wondering if anyone could tell me if the above command is wrong or another way to call a JavaScript function from a c# function. And also, if it is possible to

P.S. I am not sure what the necessary directories are for using the commands above. Those are the ones that I am using right now:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Data;
using System.IO;
using System.Data.SqlClient;

Thanks in advance!

  • Does this answer your question? [Calling JavaScript Function From CodeBehind](https://stackoverflow.com/questions/5731224/calling-javascript-function-from-codebehind) – Vivek Nuna Mar 07 '21 at 13:03
  • You should be asking why, in 2021, your school is teaching ASP.NET Web Forms. I would suggest you [use ajax techniques to call a back end end point](https://learn.microsoft.com/en-us/aspnet/web-forms/overview/older-versions-getting-started/aspnet-ajax/understanding-asp-net-ajax-web-services) instead of trying to call javascript from c#. At least that approach would have a little bit of relevance to current technology. – Crowcoder Mar 07 '21 at 13:15

1 Answers1

0

It is not obvious from your post where you are using RegisterStartupScript, did you work with web forms? Or razor pages?

Whatever you can use SignalR to trigger client from any place in your server-side code, to achieve this call task like this:

public async Task SendSignalToClients()
{
    await Clients.All.SendAsync("triggerclients");
}

And implement client side like this :

var connection = new signalR.HubConnectionBuilder().withUrl("/signalrhub").build();

connection.on("triggerclients", function (user, message) {
    alert('test')
});

connection.start().then(function () {}).catch(function (err) {
    return console.error(err.toString());
});
Grigory Zhadko
  • 1,484
  • 1
  • 19
  • 33