【问题标题】:Calling Code-behind from Javascript从 Javascript 调用代码隐藏
【发布时间】:2012-05-26 14:47:07
【问题描述】:

点击一个按钮,我调用了一个 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 asp.net button onclick


【解决方案1】:

是的,有办法。

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

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

注意:您可能需要Identifying control that caused postback

【讨论】:

  • 如果页面再次重新加载,并且是回发,我还能访问视图状态参数吗?
  • 如果你的意思是访问服务器端的视图状态,答案是肯定的。
  • 谢谢!我最终使用了您的解决方案。我将所有标记都标记为答案,因为理论上它们听起来是正确的,但我尝试了你的方法。
  • 你只能将一个标记为答案,看起来你标记了 Jesper 的答案。
  • 已更改。请看看您是否可以帮助我:stackoverflow.com/questions/10679769/…
【解决方案2】:

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

WebServiceClassName.MethodName(javascriptvariable, doSomethingOnSuccess)

这里有一个链接:

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

【讨论】:

    【解决方案3】:

    您可以调用 __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());
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-11
      • 1970-01-01
      • 1970-01-01
      • 2018-02-06
      相关资源
      最近更新 更多