更新Session变量 [英] updating Session variable

查看:69
本文介绍了更新Session变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,



i有一个母版页包含关于选择语言的下拉列表



in masterPage pageLoad我写这个代码



Hello ,

i have a master page contain dropdownlist about Selecting Language

in masterPage pageLoad i write this Code

//initial value of Session
    if (Session["DropLang_Value"] = null)
    {
        Session["DropLang_Value"] = 0.ToString();
        Session["DropLang_Text"] = English;.ToString();
    }







并将此代码写入事件 < br $> b $ b




and Write this code in Event

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
   {
     Session["DropLang_Value"] = DropDownList1.SelectedItem.Value;
     Session["DropLang_Text"] = DropDownList1.SelectedItem.Text;
   }





i有另一个Order_Now.aspx包含下拉列表并从数据库中获取数据,具体取决于下拉列表中的选定项目





立即订购.aspx代码







i have another Order_Now.aspx that contain a dropdownlist and Get data from database depending on the selected item from dropdown list


Order Now.aspx Code


public partial class Order_Now : BasePage
{
    protected void Page_Load(object sender, EventArgs e)
    {

SqlConnection con = new    SqlConnection(ConfigurationManager.ConnectionStrings["Myconecttion"].ConnectionString);
SqlCommand cmd = new SqlCommand("select*from ProductLoc where cultureid=@value", con);
cmd.Connection = con;
cmd.Parameters.AddWithValue("@value", Session["DropLang_Value"].ToString());
con.Open();
SqlDataReader r = cmd.ExecuteReader();
DropOrderType.DataTextField = "ProductName";
DropOrderType.DataValueField= "ProductId";
DropOrderType.DataSource = r;
DropOrderType.DataBind();
con.Close();      
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
    }
}







我做了breakPoint之后看看.Net采取什么方式来执行我的代码

i发现:



问题是,当我转到Order_NOW.aspx并从下拉列表中选择不同的语言时,会话变量仍然具有初始值(0)。

选择索引已更改更新值但是在我的页面之后执行:(

问题是,Session变量在Master页面的Page_Load事件后更新,并且内容页面被执行。:(叹息:: confused:



那么如何解决这个问题:-D




After i make breakPoint and see what is the way that .Net Take to Execute my codes
i found that :

The problem is that when i go to Order_NOW.aspx and select different language from dropdownlist , the session variable still have the initial value (0) .
Select index changed update the value but After my page Execution :(
The problem is that ,the Session variable is updated after the Page_Load event
from the Master page and the Content pages is executed . :( :sigh: :confused:

So How can i solve this problem :-D

推荐答案

Hercal写道:

PS: I didn't mean to necro-post. I haven't seen the original posted date for this thread as it get pushed to the top list of the current list.





首先,在为字符串 0.ToString() >。您可以这样做: string someAwesomeVariableName =0;



其次,内容页事件首先在主页事件之前触发,这就是您获得意外结果的原因。我建议你阅读: ASP.NET主页和内容页面中的事件 [ ^ ]



第三,我不建议使用 Session 在主页面和内容页面之间传递数据,因为它很难维护它。有两个选项可用于从子内容页面访问母版页的控件。



选项1:使用FindControl方法



例如,如果您的主页面中有一个 DropDownList 控件,其中 ID =ddlLanguage ,然后在你的内容页面中你可以这样做:





First off, you don't have to do 0.ToString() when assigning a default value to a string. You could simply do: string someAwesomeVariableName = "0";

Second, Content Page events trigger first before Master Page events that's why you are getting an unexpected results. I'd suggest you to read: Events in ASP.NET Master and Content Pages[^]

Third, I wouldn't recommend using Session to pass data between master and content pages as it can be hard to maintain it. There are two options that you can use to access master page's controls from child content page.

Option 1: Using FindControl method

For example, if you have a DropDownList control in your Master page with ID="ddlLanguage", then in your content page you can do:

DropDownList ddl = (DropDownList)Page.Master.FindControl("ddlLanguage"); 





如果您正在使用Data Representation控件,例如 GridView Repeater 等等。然后在母版页中查找控件可能有点棘手,特别是如果你不知道控件是如何嵌套的。你可以尝试实现一个递归的 FindControl 方法,就像这里演示的那样:母版页和FindControl



选项2:使用属性



这个选项是我的首选,因为我发现它比FindControl更容易维护并且开销更少。您需要做的是在包含DropDownList值的文件后面的主页面代码中定义一个公共属性。例如:





If you are working with Data Representation controls such as GridView, Repeater, etc.. then finding controls within master page can be a bit tricky especially if you don't know how the controls are being nested. You could try implementing a recursive FindControl method just like the one demonstrated here: Master Page and FindControl

Option 2: Using Properties

This option is my preferred as I find it easy to maintain and has less overhead compared to FindControl. What you just need to do is define a public property within your Master Page code behind file that holds the DropDownList value. For example:

public string MyPropertyOnMasterPage  
{  
        get  
        {  
            // Get value of control on master page  
            return ddlLanguage.SelectedValue;  
        }  
        set  
        {  
            // Set new value for control on master page  
            ddlLanguage.SelectedValue = value;  
        }  
} 





然后在您的DropDownList SelectedChanged事件中,您可以设置如下值:





Then in your DropDownList SelectedChanged event, you can set the value like this:

protected void ddlLanguage_SelectedIndexChanged(object sender, EventArgs e){
     MyPropertyOnMasterPage = ddlLanguage.SelectedItem.Value;
}





现在,在您的内容页面标记(.ASPX)中,您需要定义 MasterType 指令定义 VirtualPath





Now, in your content page markup (.ASPX), you need to define the MasterType directive defining VirtualPath:

<%@ MasterType VirtualPath ="~/TheVirtualPathToYourMasterPageFileHere" %>





一旦完成所有设置,您只需访问该属性您的内容页面中的MyPropertyOnMasterPage C#代码如下:





Once you have that all set, you simply access the property MyPropertyOnMasterPage in your content page C# code like this:

protected void Page_Load(object sender, EventArgs e)  { 
     string selectedLanguage = Master.MyPropertyOnMasterPage;
}





四,始终将您的代码包装在内!IsPostBack 页面加载事件中绑定控件时阻止,以避免回发中出现意外行为。





Fourth, always wrap your code within !IsPostBack block when binding a control within Page Load event to avoid unexpected behavior across postbacks.

protected void Page_Load(object sender, EventArgs e)  { 
     if(!IsPostBack){
        //your code here for binding the control
     }
}





最后,养成习惯放置食用资源的对象,例如 SqlConnection SqlCommand SqlDataReader 在using语句中,以确保对象在它们之后被正确处理和关闭用过的。以下是您的代码的更新版本:





Finally, make it a habit to put objects that eat resources such as SqlConnection, SqlCommand and SqlDataReader within a using statement to ensure that objects will be properly disposed and closed after they are used. Here's an updated version of your code:

protected void Page_Load(object sender, EventArgs e)  { 
     if(!IsPostBack){
	   string sqlStatement = "select * from ProductLoc where cultureid= @value";
   	   string connectionString = ConfigurationManager.ConnectionStrings["Myconecttion"].ConnectionString;
        	using(SqlConnection connection = new SqlConnection(connectionString)){
           		using(SqlCommand cmd = new SqlCommand(sqlStatement ,connection)){
               	 	cmd.CommandType = CommandType.Text;
       	            	cmd.Parameters.AddWithValue("@value", Master.MyPropertyOnMasterPage);
           			using(SqlDataReader reader = cmd.ExecuteReader()){
					DropOrderType.DataTextField = "ProductName";
					DropOrderType.DataValueField= "ProductId";
					DropOrderType.DataSource = reader;
					DropOrderType.DataBind();
				}
        		}
        	}
     }
}






我认为你需要考虑你的设计。

无论如何,您可以从Request.Form获取所选的下拉列表! althogh它不是一种标准方式,但它可以解决你的问题。



另一种方法可能是在你的母版页中有一个属性来传递dropdownlist对象或selectedvalue。然后从你的order_now.aspx中获取所选的值(我不确定这个解决方案但你可以测试它)这样的东西

Hi,

I think you need to consider your design.
Anyway you can get the selected drop down list from Request.Form ! althogh it is not a standard way but it may solve your problem.

Another way might be have a property in your masterpage to pass you dropdownlist object or selectedvalue. and then get the selected value from your order_now.aspx ( I am not sure about this solution but you can test it) some thing like this
cmd.Parameters.AddWithValue("@value", YourMaster.DDLProperty.SelectedValue.ToString());





只需注意在c#中你可以通过反射得到DDLProperty类似这样的事情:



just note that in c# you can get DDLProperty by using reflection something like this:

System.Reflection.FieldInfo oFI= this.Master.GetType().GetField("DDLPropertyName",System.Reflection.BindingFlags.Instance  | System.Reflection.BindingFlags.NonPublic );
DropDownList oDDL= (DropDownList)oFI.GetValue(this.Master);

cmd.Parameters.AddWithValue("@value", oDDL.SelectedValue.ToString());


这篇关于更新Session变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆