Javascript 呼叫C# 程式碼並傳遞引數的兩種方法
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" /><asp:Button <a href="javascript:TestPostValue('test')">Test Post By HiddenField</a><br/> <asp:HiddenField ID="hidden" runat="server" /> ...
<script type="text/javascript"> function TestPostValue(value) { document.getElementById("hidden").value=value; document.getElementById("Button1").click(); } </script>
protected void Button1_Click(object sender, EventArgs e) { Response.Write(hidden.Value); } 二、利用Cookies
Cookie的用法也和ASP中差不多。
比如我們建立一個名為aspcn,值為飛刀的cookie HttpCookie cookie = new HttpCookie["aspcn"]; cookie.Value = "飛刀"; Response.AppendCookie(cookie); 我們取出Cookie值也很簡單 HttpCookie cookie = Request.Cookies["aspcn"]; cookieValue = cookie.Value; 有時候我們想在一個Cookie中儲存多個資訊,那也沒有問題。比如我們在名為aspcn的cookie下加多個資訊 HttpCookie cookie = new HttpCookie("aspcn"); cookie.Values.Add("webmaster","飛刀"); cookie.Values.Add("writer","beige"); cookie.Values.Add("LinkColor","blue"); Response.AppendCookie(cookie); 取出資訊也一樣簡單 HttpCookie cookie = Request.Cookies["aspcn"]; value1 = cookies.Values["webmaster"]; value2 = cookies.Values["writer"];
View State
這是一個新出來的東東,用法和Session一樣,他的主要用途是記錄Web Control的狀態。雖然是新出來的,但是和Application、Session的用法沒有什麼區別,所以也不想詳細講解了。 State["DropLoadIndex"] = 0 ; 基本用法如上:),但是請記住,他儲存在的資訊只能在一個aspx檔案中使用。出去後,這個就沒有用了,因為他的用途只是儲存WEB控制元件的狀態。
我的實現程式碼:
<asp:Button ID="Button2" runat="server" Text="Button" OnClick="Button2_Click" />
<a href="javascript:TestPostByCookies('Test')">Test Post By Cookies</a>
function TestPostByCookies(value) { SetCookie("myCookie",value); document.getElementById("Button2").click(); } //寫cookies函式 作者:翟振凱 function SetCookie(name,value)//兩個引數,一個是cookie的名子,一個是值 { var Days = 30; //此 cookie 將被儲存 30 天 var exp = new Date(); //new Date("December 31, 9998"); exp.setTime(exp.getTime() + Days*24*60*60*1000); document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString(); } function getCookie(name)//取cookies函式 { var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)")); if(arr != null) return unescape(arr[2]); return null; } function delCookie(name)//刪除cookie { var exp = new Date(); exp.setTime(exp.getTime() - 1); var cval=getCookie(name); if(cval!=null) document.cookie= name + "="+cval+";expires="+exp.toGMTString(); }
protected void Button2_Click(object sender, EventArgs e)
{
HttpCookie cook = Request.Cookies["myCookie"];
Response.Write(cook.Value);
}