2012-05-19 84 views
3

點擊一個按鈕後,我調用一個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」?
+0

如果你使用網絡服務像加斯帕建議,請確保您知道如何保護您的Web服務。 http://stackoverflow.com/questions/4264909/asp-net-is-my-web-service-secure-enough –

回答

1

是有一種方法。

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

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

+0

如果頁面重新加載,並回發,我仍然可以訪問視圖狀態參數? –

+0

如果你的意思是在服務器端訪問查看狀態,答案是肯定的。 –

+0

謝謝!我結束了使用你的解決方案。我把所有的答案都標記爲答案,因爲理論上他們聽起來很對,但我試過了你的東西。 –

0

你可以把服務器端代碼轉換成Web服務,使在ASP服務引用:ScriptManager的你的aspx頁面上,然後你可以調用/通過從JavaScript調用執行Web服務:

WebServiceClassName.MethodName(javascriptvariable, doSomethingOnSuccess) 

這裏是做一個鏈接:

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

0

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