Can we use same datatable for pagemethod and webmethod in ASP.NET?

后端 未结 4 1459
广开言路
广开言路 2021-02-20 16:02

I am trying to create a new webpage where i need to display almost 10 different gridviews and charts.

Gridviews are binded on pageload event and charts are displayed usi

4条回答
  •  暖寄归人
    2021-02-20 16:38

    No, this is not the correct method. Since you have declared the DataTable as static (a static variable has application scope and cannot be instantiated) all

    users will get the same result (last updated values).

    You can realize this in concurrency testing.

    Please check the following scenario:

    Consider dtbl is the static dataTable which is initialized on the home page, and you create another instance of `datatable on the index page (both are in page load as given below).

    Home

    public static DataTable dtbl;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            dtbl = new DataTable();
            dtbl.Columns.Add("id");
            dtbl.Columns.Add("name");
            for (int i = 0; i < 10; i++)
            {
                DataRow dr = dtbl.NewRow();
                dr["id"] = i.ToString();
                dr["name"] = i + 1;
                dtbl.Rows.Add(dr);
            }
        }
    }
    

    Index page

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            home.dtbl = new DataTable();
        }
    }
    

    Now put a breakpoint in each page load and run the application,

    • Open both the pages in separate tab.
    • Refresh the home page and check whether the columns are showing
    • Now go to the next tab (index) and refresh it (a new instance is created for dt). It will affect the data table now you will get the new data table at home also.
    • So if these two processes/pages are concurrently executed the latest value will get for both the pages. That's why I am saying it will realize this in concurrency testing.

    You can make use of a session in this case. Consider the following code:

    Home

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            dtbl = new DataTable();
            dtbl.Columns.Add("id");
            dtbl.Columns.Add("name");
            for (int i = 0; i < 10; i++)
            {
                DataRow dr = dtbl.NewRow();
                dr["id"] = i.ToString();
                dr["name"] = i + 1;
                dtbl.Rows.Add(dr);
            }
            if (((DataTable)Session["MyDatatable"]).Columns.Count < 0)
            {
                Session["MyDatatable"] = dtbl;
            }
            else
            {
                dtbl = (DataTable)Session["MyDatatable"];
            }
        }
    }
    

提交回复
热议问题