asp.net中前台javascript與後台C#互動

來源:互聯網
上載者:User

如何在JavaScript訪問後台C#方法、變數

方法一:使用Ajax開發架構,後台方法定義前添加[AjaxPro.AjaxMethod],然後就可以在前台js指令碼中調用後台C#函數。

方法二:後台方法聲明為public或者protected,然後前台使用js指令碼進行調用。

.cs

public string Str()

{

return "javaScript函數中執行後台C#方法..";

}

.aspx

<script type="text/javascript">

var a = "<%=Str()%>";

alert(a);

</script>

方法三:使用Session變數

.cs

if (Session["siteName"] == null)//判斷是否存在指定Key值的Session變數

Session["siteName"] = "";//如果不存在則建立Session變數

//給Session["siteName"]變數賦值

.aspx

var siteName="<%=Session["siteName"] %>";

方法四

<asp:Button ID="Button1" runat="server" onclick="Button1_Click" style="display:none;"/>

<input type="button" id="btnSave " value="儲存" onclick="GetBehind ();return false;" />

.aspx.cs

<script type="text/javascript">

//調用後台方法

//使用這種方式調用後台代碼,可以在調用之前在前台做一些驗證

function GetBehind() {

document.getElementById("Button1").click();

}

</script>

.cs

protected void Button1_Click(object sender, EventArgs e)

{}

如何在後台C#代碼中執行javaScript函數

方法一:void Page.RegisterStartupScript(string key,string script);

方法二:使用隱藏欄位或者Literal控制項,在前台使用js指令碼把一些js函數控制的值寫進隱藏欄位或者Literal控制項,然後前台使用Hidden.Value或者Literal.Text讀取前台值。

.aspx

function GetTitleID(obj)

{

sTitleID=obj

if(sTitleID!=null)

document.getElementById("HiddenField1").value=type+','+sTitleID;

else

document.getElementById("HiddenField1").value=type+',0';

}

.cs

string hiddenValue = this.HiddenField1.Value;

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.