如何在C#aspnet Web表单中将变量/属性从一个方法传递到另一个方法 [英] How do I pass variables/properties from one method to another in C# aspnet web forms

查看:56
本文介绍了如何在C#aspnet Web表单中将变量/属性从一个方法传递到另一个方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,





我的Aspx页面中有以下方法。



//方法1

<前lang =c#> 受保护 void UserId( object sender,EventArgs e)
{

// 从单击按钮获取用户ID作为参数
int UserId = 231 ;


}





//方法2



 受保护  void  GetUserId( object  sender,EventArgs e)
{
int getUserId = // 如何从方法1获取userId;


}





我的尝试:



我试图把这只是在加载方法之前:



  int  Id {获取; 设置;} 



并将ID设置为userId的方法如下:

 Id = userId; 



并在方法2中调用Id,如下所示:

getUserId = Id; //但是只要我点击第一个方法,ID就会恢复为零;

解决方案

你不记得Web应用程序是无状态的。当您在一个方法上收到请求时,将返回生成的网页,并且您的状态(变量包含内容)将丢失。从浏览器调用的下一个方法是进入控制器,就像它是自启动网站以来第一次向控制器发出的请求。



如果你想要状态在调用之间维护,你必须在某个地方保持该状态,无论是在Session对象中,还是持久保存到数据库,或者你构建的其他状态管理器。



In在你的情况下,对UserId的调用需要保留你需要的变量值,然后下一次调用GetUserId需要检索该状态。但是,你还要考虑到如果国家不在那里会怎么样?如果对UserId的调用从未发生过怎么办?


Hi All,


I have the following methods in my Aspx page .

//method 1

protected void UserId(object sender, EventArgs  e)
        {

//getting user id from a button click as a parameter
             int UserId = 231;


   }



//method 2

protected void GetUserId(object sender, EventArgs  e)
        {
             int getUserId = // how do i get userId from method 1;


   }



What I have tried:

I have tried to put this just before loadpage method:

int Id {get;set;}


and set the Id to userId in method like so:

Id = userId;


and call Id in method 2 like so:
getUserId =Id; // but ID reverts back zero whenever i click the first method;

解决方案

You're not remembering that web applications are stateless. When you get a request on one method, the resulting web page is returned and your state (variables had content) is lost. The next method that is called from the browser is going to the controller like it was the first request made to the controller since the site was launched.

If you want state maintained between calls, YOU have to persist that state somewhere, be it in the Session object, or persisted to a database, or some other state manager you build.

In your case, the call to UserId needs to persist the variable values you need and then the next call, to GetUserId, needs to retrieve that state. But, you also have to account for the fact that what if the state isn't there? What if the call to UserId never happened?


这篇关于如何在C#aspnet Web表单中将变量/属性从一个方法传递到另一个方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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