如何在不刷新页面的情况下从 JavaScript 代码执行 C# 方法?

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

如何在不刷新页面的情况下从 JavaScript 代码执行 C# 方法? 这是我要执行的功能:

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);
        }
    }

我知道我应该使用

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

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

在 JS 中我使用了这段代码:

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);

}; 这就是我配置按钮的方式:

<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>

你能纠正我的错误吗? 告诉我哪里错了?

您可以使用 ASP.NET WebForm 的 UpdatePanel 控件来 运行 代码隐藏异步。这通常称为 "AJAX"(异步 JavaScript 和 XML)或 "XHR"(XML HTTP 请求),并且内置于 WebForms 框架中。

MSDN 上有一个很棒的资源可以帮助您入门:https://msdn.microsoft.com/en-us/library/bb399001.aspx

可以从 C# 窗体或 class 调用 JavaScript 函数,也可以从 JavaScript.

调用 C# 函数

Javascript 到 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# 到 Javascript

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

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