使用IF语句选择会话变量

时间:2012-01-31 15:14:03

标签: c# asp.net

我有这个代码将变量发送到另一个页面上的数据网格

 protected void Button1_Click(object sender, EventArgs e)
    {
        int agent = int.Parse(txtAgencyCode.Text);
        Session["para1"] = agent;
        Button1.Attributes.Add("onclick", "window.open('http://localhost:50771/WebSite4/Datagrid.aspx'); return false;");

    }

    protected void btnTitleSearch_Click(object sender, EventArgs e)
    {
        Session["para2"] = txtTitleSearch.Text;
        btnTitleSearch.Attributes.Add("onclick", "window.open('http://localhost:50771/WebSite4/Datagrid.aspx'); return false;");
    }

和另一个页面上的代码使用了第一个按钮的会话变量

protected void Page_Load(object sender, EventArgs e)
    {
        int field1 = (int)(Session["para"]);
        localhost.Service ws = new localhost.Service();
        GridView1.DataSource = ws.GetJobsByAgencyID(field1);
        GridView1.DataBind();
    }

我无法弄清楚如何制作一个if语句(或者即使它将是一个使用的if语句)来决定将哪个参数传递给我的datagrid。

有关信息,默认页面上将有另外3-4个控制器(其中只有一个将被激活),参数将采用不同的类型。

修改 很抱歉,你们都发现我的问题很难理解,我绝不是一个专业人士甚至是你们所谓的称职者。 James Hill和Ravi给了我很多我想要的东西(需要测试,但看起来像它)。谢谢大家的尝试:D

4 个答案:

答案 0 :(得分:2)

你的问题有点难以理解。我想你要问的是如何确定会话变量是否存在。为此,只需使用:

if (Session["para"] != null) {
    //para exists
}
else if (Session["para2"] != null) {
    //para2 exists
}
...

答案 1 :(得分:2)

如果我理解正确,您需要根据会话中存储的值进行分支,

你可以这样尝试

  if (Session["para1"] != null) 
    {
      int AgentCode = Convert.ToInt32(Session["para1"].ToString());

      //Search by AgentCode 
           GridView1.DataSource = ws.GetJobsByAgencyID(AgentCode );
            GridView1.DataBind();

    }

   else if (Session["para2"] != null)
    {
      string title = Session["para1"].ToString();

       //Search by title
       GridView1.DataSource = ws.GetJobsByAgencyID(title );
        GridView1.DataBind();
    }
   else
   {
      // your default parameters
    }

答案 2 :(得分:0)

如果数据不敏感,而不是设置会话变量,我建议在windowopen中使用查询字符串并以这种方式传递参数。

 Button1.Attributes.Add("onclick", "window.open('http://localhost:50771/WebSite4/Datagrid.aspx?dataPassed=1'); return false;");

在网格后面的代码中,做一个case语句:

int data= (int)(Request.Querystring["dataPassed"]);
switch(data)
{  case 1:
       dosomething();
       break;
   case 2:
       dosomethingelse();
       break
   default:
      throw;
      break:
}

答案 3 :(得分:0)

为什么不能有另一个名为context的会话变量?

string context = Session["context"];

switch(context)
{
case "titlesearch":
//do the things 
break;

}
不检查

语法,只检查这个想法。

相关问题