How to execute a C# method from JavaScript code without refreshing the page?

1.7k views Asked by At

How can i execute a C# method from JavaScript Code without refreshing the page? this is the function that i want to execute:

protected void submitData(object sender, EventArgs e)
    {
        MySqlConnection conn = new MySqlConnection();
        string worker = workerNameInput.Text;
        string project = projectNameInput.Text;
        string status = statusInput.Text;
        string color = colorInput.Text;
        if (worker.Equals("") || project.Equals("") || status.Equals("") || color.Equals(""))
            return;
        try
        {
            conn = new MySqlConnection();
            conn.ConnectionString = connectionString;
            conn.Open();
            string com = "insert into " + table + " values ('" + worker + "','" + project + "','"+ status + "','"+ color + "');";
            MySql.Data.MySqlClient.MySqlCommand command = new MySql.Data.MySqlClient.MySqlCommand(com, conn);
            string res = command.ExecuteNonQueryAsync().ToString();
            Console.WriteLine(res);
            Console.WriteLine("Insert command pass successfully");
        }
        catch (Exception ex)
        {
            Console.WriteLine("Failed to update database with \"insert\" command");
            Console.WriteLine(ex.Message);
        }
    }

and i know that i should use

public partial class Home : System.Web.UI.Page, IPostBackEventHandler and

public void RaisePostBackEvent(string eventArgument)
    {
        submitData(null, null);
    }

inside the JS i used this code:

project.updateTable = function() {
var projectName = project.projectName();
var workerName = project.workerName();
var status = project.status();
var color = project.color();;
if (projectName == "" || workerName == "" || status == "" || color == "")
    return;
project.rows.push({ projectName: ko.observable(projectName), workerName: ko.observable(workerName), status: ko.observable(status), color: ko.observable(color) });
project.projectName("");
project.workerName("");
project.status("");
project.color("");
var argumentString = projectName + "," + workerName + "," + status + "," + color;
var pageId = '<%= enterToDB.ClientID%>';
__doPostBack(pageId, argumentString);

}; This is how i configure my button:

<p><asp:Button runat="server" ID="enterToDB" Text="Add Project" data-bind="click: updateTable" onmouseover="this.style.background='orange', this.style.color='darkslateblue'" onmouseout="this.style.background='darkslateblue', this.style.color='orange'" /></p>

Can you correct my mistakes please? and show me where i'm wrong?

2

There are 2 answers

1
CoolBots On BEST ANSWER

You can use ASP.NET WebForm's UpdatePanel control to run the code-behind async. This is commonly known as "AJAX" (Asynchronous JavaScript and XML) or "XHR" (XML HTTP Request), and is built-in to the WebForms framework.

Here's a great resource on MSDN to get you started: https://msdn.microsoft.com/en-us/library/bb399001.aspx

0
Graffito On

It is possible to call JavaScript functions from C# form or class and to call C# functions from the JavaScript.

Javascript to C#

-------C# code--------------------
[System.Runtime.InteropServices.ComVisible(true)]
// execute the following instruction in the form initialisation
WebBrowser1.ObjectForScripting = this ;
// define a public method
public void ShowMessage (string msg) { MessageBox.Show(msg); }

-------HTML and Javascript----------------
<input type="button" value="JavaScript is calling Dotnet"
onclick="window.external.ShowMessage('JavaScript message');" />

C# to Javascript

-------C# code--------------------
object [] MyArgs = { "Hello" } ;   WebBrowser1.Document.InvokeScript("MyJsFunction",MyArgs ) ;

-------Javascript----------------
function MyJsFunction(s)  { alert(s) ; }