在asp.net中以表单形式保存数据

时间:2014-02-20 07:58:29

标签: c#

我有一个简单的查询表格,其中包括名字,姓氏等....首先我将记录插入其中但是当我点击提交按钮时它说你必须先登录才能提交查询。所以我登录到网站,我需要我第一次插入在查询表格中的网站的数据.....如何继续保持该数据??? .....所以我不需要再写一遍。 这是我的代码:

protected void btnSubmit_Click(object sender, EventArgs e)
    {
        try
        {
            if (Session["userid"] != null)
            {
                if (FileUpload1.HasFile)
                {
                    string str = FileUpload1.FileName;
                    FileUpload1.PostedFile.SaveAs(Server.MapPath(".") + "//images//" + str);
                    string path = "~//images//" + str.ToString();
                    con.Open();
                    con.Close();
                    Label1.Text = "File uploaded successfully";
                    main addinfo = new main();
                    string Id = Request.QueryString["id"];
                    string SQL = "insert into mandir(user_id,name,place,description,with_religion_category,with_district,with_religion,photo)values('" + Session["userid"] + "','" + txttemplename.Text.Trim() + "','" + txtaddress.Text.Trim() + "','" + txtdescription.Value + "','" + ddlreligioncategory.SelectedItem.Value + "','" + ddlreligion.SelectedItem.Value + "','" + ddldistrict.SelectedItem.Value + "','" + path + "')";
                    addinfo.saveData(SQL);
                    txttemplename.Text = "";
                    txtaddress.Text = "";
                    txtdescription.Value = "";
                    lblenquirymsg.Text = "Thank you for providing the information";
                }
                else
                {
                    Label1.Text = "File not uploaded successfully";
                }
            }

            else
            {
                lblinfo.Text = "You Must Login Or Register To give information";

            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("{0} Exception caught.", ex);
        }
    }
}

2 个答案:

答案 0 :(得分:0)

您可能想要使用会话。会话使用存储在客户端中的cookie。我个人使用这种方法,它完全符合我的需要:)这样的一个例子是......

Session["whatevername"]=username; 

如果你想从这个值中检索数据,就好像会话ID仍在使用中,那么......

if (Session["whatevername"]!=null)
{
  //Whatever you want to do...
} 

除此之外......另一种方法是直接将值保存为cookie ...假设您只需按下登录按钮...在按钮点击事件下添加此代码...

HttpCookie cookie = new HttpCookie("cookieid");
cookie.Values.Add("Username", Username.Text);
cookie.Values.Add("Password", Password.Text);

重新加载表单时...您可以创建一个代码来检测是否存在这样的Cookie,而不是再次输入凭据...将其置于加载事件...

if (HttpContext.Current.Request.Cookies["cookieid"] != null)
{
    Username.Text = HttpContext.Current.Request.Cookies["cookieid"]["Username"].ToString();
    Password.Text = HttpContext.Current.Request.Cookies["cookieid"]["Password"].ToString();
}

答案 1 :(得分:0)

登录成功后,您需要创建会话变量。例如:

Session["userid"] = username;

由于您的代码检查以“userid”作为值的会话。 username应该是您插入的文本框值。