我的asp网页上有这个代码(这是一个ID为www.example.com/GestHC.aspx?pID=36006394的网址)
public partial class GestHC : WebPart
{
public GestHC ()
{
}
static int iIDHC;
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
InitializeControl();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!this.Page.IsPostBack)
{
iIDHC = -1;
string str = this.Page.Request["pID"];
iIDHC = int.Parse(str.Replace("'", ""));
MyModel hc = MyModel.readdata(iIDHC);
this.txtName.text = hc.name
this.txtSurname.text = hc.surname
...
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
try
{
MyModel hc = new MyModel();
if (iIDHC != -1)
{
hc = MyModel.readdata(iIDHC);
}
else
{
hc.name = txtname.text;
hc.surname = txtSurname.text;
}
hc.dir1 = dir.text;
...
hc.savedata()
}
catch (Exception)
{
this.navegarAGridMensaje("Error");
}
}
}
问题在于,当用户加载数据并保存数据时,一切正常,但当超过2个用户或浏览器一起工作时,数据会混合在一起。例如:
User a creates:
ID = 10
Name = XXX
Age = 8
User b creates:
ID = 11
Name = YYY
Age = 10
然后,如果用户a更新了他的数据(ID = 10),可能将Age
设置为80
,结果是
User a creates:
ID = 10
Name = XXX
Age = 8
User b creates:
ID = 11
Name = YYY
Age = 88
所以(ID = 11)更新了。 Debuggin ..我可以看到使用静态id,当第二个用户加载它时可以读取以前的用户iIDHC ....
如何避免这个问题?
答案 0 :(得分:1)
您可以改为使用Session对象(https://msdn.microsoft.com/en-us/library/ms178581.aspx)。
当您将数据存储在静态变量中时 - 它将在您应用中的所有用户之间共享。
答案 1 :(得分:0)
Make it non static!
public partial class GestHC : WebPart
{
public GestHC ()
{
}
private int iIDHC = -1;//initialize here
...
}
also you dont have to initialize in page load
protected void Page_Load(object sender, EventArgs e)
{
//iIDHC = -1; - not required as you can initialize it during declaration
}