Search code examples
javascriptc#asp.netwebformsobjectdatasource

C# variable value only update once when called in Javascript


I've look an found only a similar post and didn't really answer my question or maybe they did but I didn't understand. The post I read was this one: Why does this javascript variable I'm creating via C# only get updated once?

I'm using a paged gridview and every time it's object data source runs the SelectCountMethod, I use the returning value on javascript. But, I've noticed that even thought that same returned value changes, on the server side. On javascript this value doesn't update.

My program is quite long but I'll use a basic example and hopefully some of you will understand it.

Client side:

function SomeFuntion()
{
    alert("<%=num%>");
}

Server side:

//Global variable
Public Static int num = 0;

Public int SelectCountMethod()
{                  
    var num = SomeMethod(); //Returns int

    return num;
}

For example, on the server side num returns 60 and then this value updates to 7. On the server side num equals 7 but on the client side it's still 60. Is there a way to update the client sides value?

I apologies for my poor typing skills, English is not my native language. Some examples might be helpful and thanks in advance.

I noticed that it doesn't mater where I update this variable(on selectCount method or any other method), on the client side doesn't update.


Solution

  • I found a possible solution, inefficient, but it will have to do. I have a search textbox that every time the search button is clicked, updates the grid view with the retrieved data from a data base. When the Onclick is called it binds the data source with the gridView. What I did was call the SelectCountMethod again right below the binding and used the same parameters I had stored on the Object data source as paramaters for the selectCountMethod. Then the amount returned by the selectCount I stored it on a hiddenField and that's it.

    //Global variables
    string _param1 = string.Empty,
           _param2 = string.Empty;
    
    //On click method for search btn
    protected void OnSearch(object sender, EventArgs e)
    {
        gv.DataBind();
    
        someHiddenField = SelectCountMethod(param1, param2); 
    }
    
    protected void OnSelecting(object sender, ObjectDataSourceSelectingEventArgs e)
        {
            try
            {
                e.InputParameters["Param1"] = param1;
    
                _param1 = param1                
    
                e.InputParameters["Param2"] = param2; 
    
                _param2 = param2;      
            }
            catch (Exception ex)
            {
                cvServerError.IsValid = false;
                cvServerError.ErrorMessage = ex.Message;
            }
        }