简体   繁体   English

从一个C#asp.net页到下一期的简单信息发布

[英]Simple post of info from one c# asp.net page to the next issue

I am not using MVC but forms authentication. 我不使用MVC,但使用表单身份验证。 I am having trouble getting variable to store when the submit button is pressed. 按下提交按钮时,我无法获取要存储的变量。 I have spend 2 days researching how to do this. 我花了2天的时间研究如何做。 At this point I am just trying to get the username to post on the next page. 在这一点上,我只是想让用户名发布在下一页上。 I truly thought I understood the way viewstate worked after doing this for a year. 我真的以为我已经了解了viewstate一年后的工作方式。

Code: 码:

protected void Page_Load(object sender, EventArgs e)
    {

        if (IsPostBack) {
            string username = Page.Session["username"].ToString();
            Response.Write(username);
        }

    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        Page.Session["username"] = txtUsername.Text;
    }

So after some searching I found the issue. 因此,经过一些搜索,我发现了问题。 Your code is valid, however, the postback happens BEFORE your Page.Session["username"] = txtUsername.Text; 您的代码有效,但是,回发发生在Page.Session["username"] = txtUsername.Text; which means that if you sat there and clicked the button again, you should see the results. 这意味着如果您坐在那里并再次单击该按钮,您应该会看到结果。

I was hesitant to post this until I figured out a way to fix it (because who cares why you're having a problem if there is no solution) and I figured it out. 我一直在犹豫要发布此问题,直到我想出一种方法来解决它(因为谁在乎如果没有解决方案,您为什么会遇到问题),我就知道了。 You need to change the "UseSubmitBehavior" to false for the button. 您需要将按钮的“ UseSubmitBehavior”更改为false。 So your Page_Load would look like this: 因此,您的Page_Load如下所示:

protected void Page_Load(object sender, EventArgs e)
{
    if(IsPostBack) {
        string username = Page.Session["username"] as string; // will be null if empty
        Resopnse.Write(username);
    }
    btnSubmit.UseSubmitBehavior = false;
}

That should allow the value in txtUsername to be put into the Session variable before the postback and thus you will have access to it in the page load. 这应该允许在回发之前将txtUsername中的值放入Session变量中,这样您就可以在页面加载中访问它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM