从 Javascript 调用代码隐藏

Calling Code-behind from Javascript

本文关键字:隐藏 代码 调用 Javascript      更新时间:2023-09-26

单击按钮时,我调用JavaScript函数。获取值后,我需要从代码隐藏中获得的值中执行一些操作。我应该如何调用代码隐藏?

我的aspx:

function openWindow(page) {
  var getval = window.showModalDialog(page);
  document.getElementById("<%= TxtInput.ClientID %>").value = getval; 
  //After this I need to perform stuff 'Upload(TxtInput.value)' into database from the code-behind
}

调用函数的按钮按以下方式设置:

<button class="doActionButton" id="btnSelectImage" runat="server" onclick="openWindow('../rcwksheet/popups/uploader.htm')">Select Image</button>

我想要的代码隐藏(VB(:

Public Sub btnSaveImage_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSelectImage.ServerClick
  Dim inputFile As String = Me.TxtInput.Value
  //do more stuff here
End Sub

所以:

  1. 有没有办法从 JavaScript 调用代码隐藏?
  2. 我可以以某种方式使用按钮的"onclick"属性首先转到JavaScript,然后转到代码隐藏吗?
  3. 触发 TxtInput.Value 的代码隐藏调用"onchange"?

是的,有一种方法。

首先,您可以使用 JavaScript 在 TxtInput 中设置返回值后提交表单。

function openWindow(page) {
  var getval = window.showModalDialog(page);
  document.getElementById("<%= TxtInput.ClientID %>").value = getval; 
  document.forms[0].submit();
}

然后在代码隐藏中,可以在页面加载事件中处理TxtInput 的值。

protected void Page_Load(object sender, EventArgs e)
{
    if (Page.IsPostBack)
    {
        if (this.Input.Value != string.Empty)
        {
            this.Input.Value += "blah";
        }
    }
}

注意:您可能需要识别导致回发的控件

您可以将服务器端代码放入 Web 服务中,在 aspx 页上的 asp:ScriptManager 中进行服务引用,然后可以通过调用以下命令从 JavaScript 调用/执行 Web 服务:

WebServiceClassName.MethodName(javascriptvariable, doSomethingOnSuccess)

这是执行此操作的链接:

http://msdn.microsoft.com/en-us/magazine/cc163499.aspx

您可以调用__doPostBack事件。

function openWindow(page) {
  var getval = window.showModalDialog(page);
  document.getElementById("<%= TxtInput.ClientID %>").value = getval; 
__doPostBack('btnSelectImage', getval);
}

而在服务器端的代码隐藏中,你可以得到值:

在 PageLoad 方法中:

if (Request.Form["__EVENTTARGET"] == "btnSelectImage")
{
    //get the argument passed
    string parameter = Request["__EVENTARGUMENT"];
    //fire event
    btnSaveImage_Click(this, new EventArgs());
}