【问题标题】:Call c# function through javascript [closed]通过javascript调用c#函数[关闭]
【发布时间】:2016-09-05 21:51:03
【问题描述】:

您好,我正在尝试使用 JavaScript 中的传递变量调用 c# 函数,我该怎么做? JavaScript

    <span id="range">0</span>

    function showValue(newValue)
    {
        i need to Call a csharp function here with the newValue var
    }

【问题讨论】:

  • 这是 MVC 吗?这是在 .cshtml 文件还是 .js 文件中?在将 html 渲染回客户端之前,您需要在客户端(不可能,至少在没有一些额外编码的情况下)或服务器端实际调用 C# 函数?

标签: javascript c# asp.net websocket


【解决方案1】:

你不能,因为 javascript 在浏览器中运行,c# 在服务器上。

看起来你正在做一些网络工作,这意味着你有一个服务器将内容传送到网络浏览器。

我知道的唯一替代方法是在服务器上创建一个端点(假设是一个页面),该端点将充当您的 javscript 和 c# 代码之间的代理。您将返回一些 json/xml/etc,js 将对其进行处理。

【讨论】:

  • 这不是真的哈哈
【解决方案2】:

取自http://www.dotnetcurry.com/ShowArticle.aspx?ID=109&AspxAutoDetectCookieSupport=1 更多想法Google Search

第 1 步:创建一个支持 ASP.NET AJAX 的网站。转到文件 > 新建 > 网站 > 启用 ASP.NET AJAX 的网站。为解决方案指定名称和位置,然后单击“确定”。

第 2 步:拖放 2 个标签和 4 个文本框控件。我们将在 2 个文本框中接受用户的 CustomerID,并在其他两个文本框中显示“ContactName”。将显示“ContactName”的文本框设置了一些属性,使其显示为没有边框的标签。只需设置 BorderStyle=None、BorderColor=Transparent 和 ReadOnly=True。标记将类似于以下内容:

<form id="form1" runat="server">     

    <asp:ScriptManager ID="ScriptManager1" runat="server"/>

    <div>

    <asp:Label ID="lblCustId1" runat="server" Text="Customer ID 1"></asp:Label>

    <asp:TextBox ID="txtId1" runat="server"></asp:TextBox><br />

        <asp:TextBox ID="txtContact1" runat="server" BorderColor="Transparent" BorderStyle="None"

            ReadOnly="True"></asp:TextBox><br />

    <br />

    <asp:Label ID="lblCustId2" runat="server" Text="Customer ID 2"></asp:Label>

    &nbsp;

    <asp:TextBox ID="txtId2" runat="server"></asp:TextBox><br />

        <asp:TextBox ID="txtContact2" runat="server" BorderColor="Transparent" BorderStyle="None"

            ReadOnly="True"></asp:TextBox>&nbsp;<br />

        </div>

</form>

在继续之前,我们会将连接字符串信息存储在 Web.config 中。在您的 &lt;/configSections&gt; 标签下方添加以下标签。请记住,我们已经创建了一个“启用 ASP.NET AJAX 的网站”。标签 &lt;/configSections&gt; 以及其他一些标签会自动添加到 web.config。

<connectionStrings>

        <removename="all"/>

        <addname="NorthwindConnectionString"connectionString="Data Source=(local); Initial Catalog=Northwind; Integrated Security = SSPI;"/>

  </connectionStrings>

第 3 步:目前我们将添加一个方法“GetContactName()”,该方法将接受 CustomerID 并从 Northwind 数据库 Customer 表中返回联系人姓名信息。然后我们将此方法转换为 PageMethod。

C#

public static string GetContactName(string custid)

    {

    if (custid == null || custid.Length == 0)

        return String.Empty;

    SqlConnection conn = null;

    try

    {

        string connection = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;

        conn = new SqlConnection(connection);

        string sql = "Select ContactName from Customers where CustomerId = @CustID";

        SqlCommand cmd = new SqlCommand(sql, conn);

        cmd.Parameters.AddWithValue("CustID", custid);

        conn.Open();

        string contNm = Convert.ToString(cmd.ExecuteScalar());

        return contNm;

    }

    catch (SqlException ex)

    {

        return "error";

    }

    finally

    {

        conn.Close();

    }

}

VB.NET

 Public Shared Function GetContactName(ByVal custid As String) As String

    If custid Is Nothing OrElse custid.Length = 0 Then

        Return String.Empty

    End If

    Dim conn As SqlConnection = Nothing

    Try

        Dim connection As String = ConfigurationManager.ConnectionStrings("NorthwindConnectionString").ConnectionString

        conn = New SqlConnection(connection)

        Dim sql As String = "Select ContactName from Customers where CustomerId = @CustID"

        Dim cmd As SqlCommand = New SqlCommand(sql, conn)

        cmd.Parameters.AddWithValue("CustID", custid)

        conn.Open()

        Dim contNm As String = Convert.ToString(cmd.ExecuteScalar())

        Return contNm

    Catch ex As SqlException

        Return "error"

    Finally

        conn.Close()

    End Try

End Function

第 4 步:我们现在将此方法转换为 PageMethod,然后从客户端代码调用此方法 GetContactName();即使用 JavaScript。要将方法启用为 PageMethod,请在方法顶部添加属性 [WebMethod]:

C#

[System.Web.Services.WebMethod]

public static string GetContactName(string custid)

{

}

VB.NET

<System.Web.Services.WebMethod()> _

Public Shared Function GetContactName(ByVal custid As String) As String

结束函数

同时在ScriptManager中添加属性EnablePageMethods="true"如下图:

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"/>

第 5 步:现在让我们创建将调用此服务器端代码的 JavaScript。将一个名为 script.js 的 javascript 文件添加到您的解决方案中(右键单击项目 > 添加新项目 > Jscript 文件 > 将文件重命名为 script.js)。将以下代码添加到 javascript 文件中。

function CallMe(src,dest)

 {     

 var ctrl = document.getElementById(src);

 // call server side method

 PageMethods.GetContactName(ctrl.value, CallSuccess, CallFailed, dest);

 }

// 使用 ContactName 设置目标文本框值

 function CallSuccess(res, destCtrl)

 {     

 var dest = document.getElementById(destCtrl);

 dest.value = res;

 }



// alert message on some failure

 function CallFailed(res, destCtrl)

 {

 alert(res.get_message());

 }

第 6 步:我们现在需要从我们的 aspx 页面引用这个 JavaScript 文件,并在文本框失去焦点时调用“CallMe()”方法。这样做:

在body标签中添加对javascript文件的引用,如下所示:

<body>

<script type="text/javascript" language="javascript" src="script.js">          </script>

<form id="form1" runat="server">     

…………

第 7 步:要在文本框失去焦点时调用方法,请在 Page_Load() 事件中添加这些代码行

C#

if (!Page.IsPostBack)

    {

        txtId1.Attributes.Add("onblur", "javascript:CallMe('" + txtId1.ClientID + "', '" + txtContact1.ClientID + "')");

        txtId2.Attributes.Add("onblur", "javascript:CallMe('" + txtId2.ClientID + "', '" + txtContact2.ClientID + "')");

    }

VB.NET

If (Not Page.IsPostBack) Then

              txtId1.Attributes.Add("onblur", "javascript:CallMe('" & txtId1.ClientID & "', '" & txtContact1.ClientID & "')")

              txtId2.Attributes.Add("onblur", "javascript:CallMe('" & txtId2.ClientID & "', '" & txtContact2.ClientID & "')")

End If

如上所示,我们使用了 Attributes.Add,它允许我们向服务器控件的 System.Web.UI.AttributeCollection 对象添加一个属性。将调用保存在“script.js”文件中的函数“CallMe”。我们将源文本框和目标文本框作为参数传递。源文本框将包含 CustomerID。将在客户表中查找客户 ID,并在目标文本框中检索相应的“联系人姓名”。

这就是从客户端调用服务器端代码所需的全部内容。运行代码。在第一个文本框中输入“ALFKI”,然后按 Tab 键。您将看到 javascript 函数继续运行并使用 PageMethods.GetContactName 调用 PageMethod GetContactName()。它传递包含 CustomerID 的源文本框的值。返回的“ContactName”显示在第一个文本框下方的第二个文本框中,在我们的例子中显示的值为“Maria Anders”。

疑难解答:“PageMethods Is 'Undefined'”错误

  1. 尝试在脚本管理器标签中设置 EnablePageMethods="true"

  2. 不要在&lt;head /&gt; 部分添加javascript 引用或代码。将其添加到&lt;body&gt; 标记中。

  3. 页面方法需要在后面的代码中是静态的。

我希望您对如何使用 JavaScript 调用服务器端代码有所了解。我已经在一些项目中成功地使用了这种技术,并且非常喜欢和欣赏 PageMethods。我希望你觉得这篇文章有用,我感谢你查看它。本文的源代码可以从这里下载。

【讨论】:

  • 哇,您发布了很多代码只是为了让某人投反对票。这个答案肯定可以缩短以适应用户的情况,更不用说互联网上有很多工作示例以及堆栈溢出
  • 是的,我认为这个问题无论如何都会被标记和删除。我想我应该得到DV。我知道 SO 规则不适合发布将来可能会更改的链接,所以我只是粘贴了。
  • 你作为发帖者可以删除这个。我认为如果你展示一个如何从 JavaScript 中调用 c# 函数的小例子就足够了,更不用说除了发布问题外,OP显然没有自己做任何研究..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-06-28
  • 1970-01-01
  • 2021-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多