简体   繁体   English

JS中C#var的asp.net值

[英]asp.net value of C# var in JS

I have a simple JS pop up "are you sure..." window, along with a dropdownlist and asp:button . 我有一个简单的JS弹出"are you sure..."窗口,还有一个dropdownlist和asp:button What I want when I click the button is to get this message: 当我单击该按钮时,我想要的是以下消息:

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

where ACTION is a string coming from dropdownlist.SelectedItem.Text. 其中ACTION是来自dropdownlist.SelectedItem.Text的字符串。

The following does not seem to work: 以下似乎无效:

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

It actually just prints the <%= ACTION %> instead of the value. 实际上,它只是打印<%= ACTION %>而不是值。

I have also tried: 我也尝试过:

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

OnClientClick="testMe();"

But the above causes postback regardless of clicking cancel or OK . 但是,无论单击“ cancel或“ OK ,以上内容都会导致回发。

Which is the correct usage? 正确的用法是?

You can't use server tags inside of server control declarations. 您不能在服务器控件声明中使用服务器标签。 Set the OnClientClick script in the code behind when initialising the object. 初始化对象时,在后面的代码中设置OnClientClick脚本。

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

Try this: 尝试这个:

<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();" />

Sorry, my last answer was complete garbage (didn't think before posting). 抱歉,我的最后一个答案是完整的垃圾(发布前没有想到)。 What about this (you're almost right)? 那怎么办(您几乎是对的)?

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

OnClientClick="return testMe();"

You just missed the return on the OnClientClick. 您只是错过了OnClientClick的回报。

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

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