2013年9月23日 星期一

Html 傳值的幾種方式

簡單介紹一下Html傳值得幾種寫法 ,網頁大致來分有兩種傳值方式 "Get" 和 "Post"

先從 "Post" 部分開始介紹:

        <form id="Post" method="post"> 
            <input type="text" runat="server" id="Data"> 
            <input id="button1" type="button" value= "java" onclick="post();" runat="server"> 
        </form>

        <script language="javascript">
            function post() {
                Post.action = "NextPage.aspx";
                Post.submit();
            } 
        </script>

接值頁面

string data=Request.Form["Data"].ToString();

另一種不用Javascript 使用Name 來接值的方式

            <form  method="POST" action="NextPage.aspx"> 
   <p><input type="text" name="Textbox"></p> 
   <p><input type="submit" value="確定" name="submit2"></p> 
   </form> 

接值頁面

 string a = Request.Form["Textbox"].ToString();

使用 "Get" 方式

            string id=123;
            string passwod=123;
         
            Response.Redirect("NextPage.aspx?id=" + id + "&password=" + password);

接值頁面

            string id=Request.QueryString[" id"].ToString();
            string password=Request.QueryString[" password"].ToString();

另一種用 " Get" 接值的方式

<select id="childrenValue" name="childrenValue">
                             <%= childrenValue %>
                        </select>

<input id="Button1" type="button" value="123" onclick="htmlchange()"  />

 function htmlchange() {

//childrenValue 為下拉式選單

        if ($("#childrenValue").val() == "請選擇") {
            alert("尚未選擇結點");
        }
        else {
            window.location.href = "Management/Node/CreateNewLevel.aspx?childrenValue=" + $("#childrenValue").val();
        }

    }

接值頁面

 ParentIdLabel.Text = Request.QueryString["childrenValue"];

在這邊可以注意到 "Post" 的接值方式是使用 Request.Form "Get" 是使用 Request.QueryString

那如果遇到本頁的後端想要拿到本頁前端的某一個 input type = text 要怎麼辦呢?

<input type="text" name="TextBox" value="123">

那本頁後端就可以直接使用name的變數來抓取(注意不是使用Id)

 string id = Request["TextBox"];


沒有留言:

張貼留言