繁体   English   中英

从Javascript调用代码隐藏

[英]Calling Code-behind from Javascript

点击一个按钮,我调用一个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”?

是的,有办法。

首先,您可以在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";
        }
    }
}

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

您可以将服务器端代码放入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());
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM