在.NET环境中,经常需要从客户端JavaScript触发后端事件,并传递数据。本文将介绍如何通过JavaScript在.NET中触发后端事件,并传递字符串变量。本文允许从JavaScript传递变量。
首先,需要定义一个EventArg类来存储传递的参数:
Public Class JavaScriptPostbackEventArgs
Inherits EventArgs
Public args As String = ""
Public Sub New(args As String)
Me.args = args
End Sub
End Class
接下来,需要修改PostBack事件的类型以使用这个新类:
Public Event Postback As EventHandler(Of JavaScriptPostbackEventArgs)
然后,需要修改JavaScript函数,以便能够传递一个字符串变量:
Protected Overrides Sub Render(writer As HtmlTextWriter)
MyBase.Render(writer)
Dim options As New PostBackOptions(PostbackButton)
options.PerformValidation = Me.CausesValidation
options.ValidationGroup = Me.ValidationGroup
options.Argument = "arg"
Dim functionName__1 As String = If(JavaScriptNamespaces.Equals(String.Empty), FunctionName, String.Concat(JavaScriptNamespaces, ".", FunctionName))
Dim arg As String = "e"
writer.Write("")
Me.Page.ClientScript.RegisterForEventValidation(options)
End Sub
最后,需要在后端事件处理中获取EventArgument:
Private Sub PostbackButton_Click(sender As Object, e As EventArgs)
RaiseEvent Postback(sender, New JavaScriptPostbackEventArgs(HttpContext.Current.Request("__EVENTARGUMENT")))
End Sub
以上是所有需要的更改。
以下是如何在客户端使用它的示例。在页面标记中添加控件:
一个简单的JavaScript示例调用函数:
最后是处理事件的后端代码:
Private Sub ucJavascriptpostback_Postback(sender As Object, e As JavaScriptPostbackEventArgs) Handles ucNodeClickPostback.Postback
End Sub