2012-07-19 53 views
0

我有一個簡單的JS彈出"are you sure..."窗口,還有一個下拉列表和asp:button。 我想,當我按一下按鈕是爲了得到這個消息:asp.net c#var var in JS

"Are you sure you want to perform <%= ACTION %>?"

採取行動時,從dropdownlist.SelectedItem.Text來的字符串。

下似乎並沒有工作:

OnClientClick="return confirm('Are you sure you want to perform <%= ACTION %>?); 

它實際上只是打印<%= ACTION %>,而不是價值。

我也曾嘗試:

function testMe() { 
    return confirm('Are you sure you want to perform ' + document.getElementById('<%= hfAction.ClientID %>').value + '?'); 
} 

OnClientClick="testMe();" 

但上述原因回傳,無論點擊cancelOK的。

這是正確的用法?

+0

如何在C#代碼中定義ACTION – Habib 2012-07-19 12:43:52

+0

是它的簡單字符串。 – user1468537 2012-07-19 12:46:19

回答

2

試試這個:

<asp:DropDownList runat="server" ID="ACTION"> 
    <asp:ListItem>Action 1</asp:ListItem> 
    <asp:ListItem>Action 2</asp:ListItem> 
</asp:DropDownList> 

<script type="text/javascript"> 
    function ExecuteConfirm() { 
     var ddlId = '<%= ACTION.UniqueID %>'; 
     var action = $("#" + ddlId + " option:selected").text(); 
     return confirm('Are you sure you want to perform ' + action + ' ?'); 
    } 
</script> 

<asp:Button runat="server" Text="Button" OnClientClick="return ExecuteConfirm();" /> 
+0

Microsoft JScript運行時錯誤:屬性'$'的值爲空或未定義,而不是Function對象 – user1468537 2012-07-19 13:51:50

+0

我在示例代碼上使用了jquery。你可以使用「var action = document.getElementById(ddlId).value;」而不是像那樣包含「var action = $ ...」 – 2012-07-19 14:03:13

+0

好吧,我只是在頭上缺少導入。現在工作正常。謝謝:) – user1468537 2012-07-19 14:27:17

2

您不能在服務器控件聲明中使用服務器標籤。初始化對象時,在後面的代碼中設置OnClientClick腳本。

mybutton.OnClientClick 
    = string.format("return confirm('Are you sure you want to perform {0}?');", ACTION); 
+0

這也沒有工作 – user1468537 2012-07-19 13:49:20

+0

在什麼意義上?同樣的問題?錯誤? – 2012-07-19 13:54:39

1

對不起,我最後的答案是完整的垃圾(沒想到發佈之前)。這個怎麼樣(你幾乎是正確的)?

function testMe() { 
    var val = document.getElementById('<%= hfAction.ClientID %>').value; 
    return confirm('Are you sure you want to perform ' + val + '?'); 
} 

OnClientClick="return testMe();" 

你剛剛錯過了OnClientClick的回報。

+0

幾乎在那裏。我遇到的問題是,在我選擇DDL上的另一個項目後,它沒有獲取hfAction.value的新值。如果我只做了回發,那麼它會提取價值。我這樣設置:'protected void ddlActions_SelectedIndexChanged(object sender,EventArgs e) { hfAction.Value = ddlActions.SelectedItem.Text; }' – user1468537 2012-07-19 14:16:50

+0

那你能不能直接查詢DDL而不是hfAction?那麼document.getElementById('ddlActions.ClientID')。value? – 2012-07-19 14:32:18