且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

阿贾克斯PageMethod的访问页面级的私有静态属性

更新时间:2023-12-03 09:07:28

您的问题是这样的:

 私有静态诠释SelectedYear;
 

您将要删除静态。静态意味着它的全球性,将所有用户/请求共享......所以,当你将其设置为2013一个用户,其他用户点击尚未选定一年谁该网页,它会被设置为0 .. 。对他们俩的。哎呀!

通过你的回传跟踪,看看发生了什么事情该变量在你的AJAX方法。

您应该考虑在页面上存储的值在会话变量或者在一个隐藏字段。

多看书上类似的帖子:ASP.NET C#静态变量是全球性的?

I have a page that uses Ajax Page Methods. When the page first loads, the user is prompted to select a year. This is the only time that a PostBack occurs. The year is stored in a private static page-level integer property named SelectedYear. There are several page methods that pass data from the client to the server, but the year is always stored on the server, so that it won't have to be to be passed in again. The problem is, in a few cases, within the server WebMethod, the SelectedYear property seems to be reverting to 0. I can test for 0 and throw the error back to the client, but it would help if I could explain why it happened. At this point, I don't know. Any ideas? I'm a bit new to this style of programming. Here's a (very simplified) example of the code. The user MUST have selected a year in order to ever have reached the save function.

Here is my C# server code:

public partial class Default : System.Web.UI.Page
{
    private static int SelectedYear;

    protected void YearSelected(object sender, EventArgs e)
    {
        if (sender.Equals(btnCurrentYear))
            SelectedYear = 2013;
        else
            SelectedYear = 2014;
    }

    [WebMethod]
    public static bool Save(string FirstName, string LastName)
    {
        try
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
                //Right here, SelectedYear is sometimes 0.
                SaveApplication(FirstName, LastName, SelectedYear);
            else
                throw new Exception("User is not logged in.");
        }
        catch (Exception ex)
        {
            throw;
        }
    }
}

Here is my JavaScript client code:

function Save(FirstName, LastName) {
    PageMethods.Save(firstName, LastName, SaveSucceeded, SaveFailed);
}

function SaveSucceeded(result) {
    //Notify user that save succeeded.
}

function SaveFailed(error) {
    //Notify user that save failed.
}

Your problem is this:

 private static int SelectedYear;

You'll want to remove the static. Static means it's global and will be shared for all users/requests... so when you set it to 2013 for one user, and another user hits that page who hasn't yet selected a year, it will be set to 0... for both of them. Yikes!

Trace through your postbacks to see what is happening to that variable during your AJAX methods.

You should consider storing the value in a session variable or maybe in a hidden field on the page.

More reading on a similar post: ASP.NET C# Static Variables are global?