您好我试图用JavaScript中的传递变量调用c#函数我该怎么做? JavaScript的
<span id="range">0</span>
function showValue(newValue)
{
i need to Call a csharp function here with the newValue var
}
答案 0 :(得分:0)
你不能因为javascript在浏览器中运行,c#就在服务器上。
看起来你正在做一些网络内容,这意味着你有一台服务器将内容传送到网络浏览器。
我知道的唯一选择是在服务器上创建服务器上的端点(比如一个页面),它将充当javscript和c#代码之间的代理。你将返回js将使用的一些json / xml / etc。
答案 1 :(得分:-1)
取自http://www.dotnetcurry.com/ShowArticle.aspx?ID=109&AspxAutoDetectCookieSupport=1 Google Search
的更多想法步骤1:创建启用ASP.NET AJAX的网站。转到文件&gt;新&gt;网站&gt;支持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>
<asp:TextBox ID="txtId2" runat="server"></asp:TextBox><br />
<asp:TextBox ID="txtContact2" runat="server" BorderColor="Transparent" BorderStyle="None"
ReadOnly="True"></asp:TextBox> <br />
</div>
</form>
在继续之前,我们将把连接字符串信息存储在Web.config中。在</configSections>
标记下添加以下标记。请记住,我们已经创建了一个“支持ASP.NET AJAX的网站”。标记</configSections>
以及其他一些标记会自动添加到web.config。
<connectionStrings>
<removename="all"/>
<addname="NorthwindConnectionString"connectionString="Data Source=(local); Initial Catalog=Northwind; Integrated Security = SSPI;"/>
</connectionStrings>
步骤3:目前我们将添加一个方法'GetContactName()',它将接受CustomerID并从Northwind数据库Customer表返回Contact Name信息。然后我们将此方法转换为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
结束功能
同时,将属性EnablePageMethods =“true”添加到ScriptManager,如下所示:
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"/>
步骤5:现在让我们创建将调用此服务器端代码的JavaScript。将一个名为script.js的javascript文件添加到您的解决方案中(右键单击项目&gt;添加新项&gt; Jscript文件&gt;将文件重命名为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。将在Customers表中查找CustomerID,并在目标文本框中检索相应的“ContactName”。
这就是从客户端调用服务器端代码所需的全部内容。运行代码。在第一个文本框中键入“ALFKI”,然后按Tab键。您将看到javascript函数继续使用PageMethods.GetContactName调用PageMethod GetContactName()。它传递包含CustomerID的源文本框的值。返回的“ContactName”显示在第一个文本框下方的第二个文本框中,在我们的示例中,显示的值为“Maria Anders”。
疑难解答:'PageMethods'未定义''错误
尝试在脚本管理器标记
中设置EnablePageMethods =“true”
请勿在{{1}}部分添加javascript引用或代码。将其添加到<head />
代码。
页面方法需要在后面的代码中保持静态。
我希望您已经了解了如何使用JavaScript调用服务器端代码。我在一些项目中成功地使用了这种技术,只是喜欢和欣赏PageMethods。我希望你发现这篇文章有用,我感谢你查看它。可以从这里下载本文的源代码。