[英]How I would call a C# function from javascript?
我試圖弄清楚如何從javascript確認框中調用C#函數。 即,如果用戶選擇“確定”,則調用一個功能,如果用戶選擇“取消”,則調用另一個功能。 所有代碼都位於背面,如下所示:
Response.Write(@"
<script language='javascript'>
var msg=confirm('Your new document has been created.\nPress OK to go there now, or Cancle to create another document.');
if (msg==true) {<%=redirect()%>;}
else {<%=clearForm()%>;}
</script>
");
protected void redirect(object sender, EventArgs e)
{
Response.Redirect("myPage.aspx");
}
protected void clearForm(object sender, EventArgs e)
{
//More code here//
}
請注意,Response.Redirect中的所有代碼都在一行上,為簡單起見,我在這里將其拆分! 無論如何,這是行不通的,我找不到解決方案。 我在if
語句中嘗試了各種不同的方法
我的第一個想法不是給用戶一個選項,而是簡單地使用:
Response.Write(@"<script language='javascript'>alert('Your new document has been created.');</script>");
Response.Redirect("TaskPanel.aspx");
但是,當我嘗試此操作時,頁面沒有等待用戶單擊“確定”再進行重定向,因此變得毫無意義。
您在服務器端代碼和客戶端代碼之間感到困惑。 您提出的C#代碼將在您的服務器上運行,並在頁面上寫出JavaScript代碼:
<script language='javascript'>
var msg=confirm('Your new document has been created.\nPress OK to go there now, or Cancle to create another document.');
if (msg==true) {<%=redirect()%>;}
else {<%=clearForm()%>;}
</script>
您寫出的JavaScript將在客戶端瀏覽器上運行。
但是,我想您會遇到JavaScript錯誤,因為它將嘗試寫出<%=redirect()%>;
和<%=clearForm()%>;
這是應該在服務器端運行的ASPX scriptlet代碼(但實際上在客戶端的JavaScript中顯示為字符串)。
這只是為什么不能直接從JavaScript調用C#函數的解釋/答案。
對於您的特定問題,您無需調用服務器即可進行重定向或清除表單。
這兩個都可以用JavaScript完成。
可以使用JavaScript window.location="myPage.aspx"
或self.location="myPage.aspx"
完成重定向
可以使用JavaScript form.reset()
來完成清除表單
是的,它很簡單:將回調函數放在文件中
之后,您應該單擊“ 確定”進行綁定,然后使用以下命令調用該函數: AJAX和任何javascript框架,以使其變得簡單
確定取消
$("#OK,#Cancel").click(function(){
var whichFct = $(this).attr('fct'); var urlToFile = "web/app/link/fct/1";
if(whichFct == 2) urlToFile = "web/app/link/fct/2"
$.post(urlToFile,function() {
//do sthlike hiding the form ...
});
});
它比這簡單
在buttonclick上傳遞一個javascript函數。然后在.aspx頁中編寫以下代碼:
<script language='javascript'>
function func_name()
{
var msg=confirm('Your new document has been created.\nPress OK to go there now, or Cancle to create another document.')
if (msg==true) {<%=redirect()%>}
else {<%=clearForm()%>}
}
</script>
其他按鈕也是如此。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.