![](/img/trans.png)
[英]How to get the value of hidden field and pass it to another aspx page? (C#)
[英]How get a value by URL in another aspx page
我有一個建立在母版頁上的表單,用於搜索用戶的存在(在sql數據庫中)。 如果在提交表單后,sql找到了某個用戶,則它應定向到新頁面並顯示該用戶的詳細信息。
我的主題是:在下一頁中,如何為該用戶保存用戶ID,以僅對該用戶執行“選擇”,並顯示其詳細信息。
我可以在主頁上使用JavaScript,還是不建議使用?
我的C#/ ASP.NET代碼是:
protected void ClientSearch(object sender, EventArgs e)
{
int i;
string query;
con.Open();
sqlcomm.Connection = con;
query = "Select * FROM Cliente WHERE Cliente.nome='" + textboxclientname.Text + "'AND Cliente.apelido='" + textboxapelido.Text + "'";
sqlcomm.CommandText = query;
SqlDataReader dr;
dr = sqlcomm.ExecuteReader();
dr.Read();
if (dr.HasRows)
{
//new page
//At that page, user data may be displayed in textboxes, to be updated
}
else
{
//show error page
}
}
將您的信息存儲在會話中
如果您要導航到單獨的頁面,則可以通過多種選擇來保留特定值:
這些中的任何一個都可以用來輕松存儲值,然后在下一頁或請求中訪問它們。
使用會話存儲的示例
因此,在您的情況下,您希望將數據庫返回的值存儲在這些元素之一中,然后在下一頁進行檢索:
protected void ClientSearch(object sender, EventArgs e)
{
using(var con = new SqlConnection("{your-connection-string}"))
{
var query = "SELECT * FROM Cliente WHERE nome = @name AND apelido = @apelido";
using(var comm = new SqlCommand(query,con))
{
con.Open();
// User parameters to avoid SQL Injection
comm.Parameters.AddWithValue("@name",textboxclientname.Text);
comm.Parameters.AddWithValue("@apelido",textboxapelido.Text);
// Get your result and store it in the Session
var id = -1;
Int32.TryParse(Convert.ToString(comm.ExecuteScalar()),out id);
if(id != -1)
{
// Store your ID in the Session
Session["UserID"] = id;
// Go to your other page
Response.Redirect("OtherPage.aspx");
}
else
{
// No user was found, do something
}
}
}
}
然后在您的OtherPage中,只需按預期從會話中讀取它即可:
if(Session["UserID"] != null)
{
// Read the value from the Session
var userId = Convert.ToInt32(Session["UserID"]);
// Do something here
}
同樣,您可以輕松創建一個cookie以在多個頁面上持久保存您的UserID值,或者在導航到其他頁面時將其簡單地附加到QueryString:
Response.Redirect(String.Format("OtherPage.aspx?userId={0}",userId));
然后通過閱讀它:
var userId = Convert.ToInt32(Request["userId"]);
檢索到ID后,可以將其在查詢字符串中傳遞到顯示用戶詳細信息的頁面,例如http://example.com/userdetails.aspx?id=1
然后,用戶詳細信息頁面可以從查詢字符串中檢索ID,並顯示該用戶的適當詳細信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.