<script language="javascript" type="text/javascript">
function myjavascriptfn()
{
//debugger;
var strValue= "test";
return strValue
}
如何在我的代码中调用此 javascript 函数并正确处理各自的返回值。
最佳答案
您可以使用以下命令轻松声明要在客户端上运行的 JavaScript:
ScriptManager.RegisterStartupScript(this, this.GetType(), "launchpage", "
function javascriptfn() {
var strValue= 'test';
return strValue;
}
document.getElementById('"+HiddenField1.ClientID+"').value = javascriptfn();
document.getElementById('"+saveProgressButton.ClientID+"').click();
", true);
注意:我已将 JavaScript 分成多行,以便于阅读,但它应该全部在一行上。
您的问题来自问题的第二部分,将数据发回,您很可能需要回发(部分或全部或使用 AJAX 处理。
我将添加一个带有 asp 隐藏字段和隐藏按钮的更新面板来触发它,用此函数的任何内容填充隐藏字段的值,并在您的代码后面有一些代码来捕获事件。
<asp:UpdatePanel ID="responcetable" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:HiddenField ID="HiddenField1" runat="server" />
<asp:Button ID="saveProgressButton" runat="server" Text="Button" CssClass="displaynone" />
</ContentTemplate>
<Triggers><asp:AsyncPostBackTrigger ControlID="saveProgressButton" EventName="theeventtodealwiththis" /></Triggers>
</asp:UpdatePanel>
在服务器端
protected void theeventtodealwiththis(object sender, EventArgs e)
{
// some logic to handle the value returned
}
关于c# - 如何在C#中调用javascript并获取返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9326635/