locked
Assigned Value To Variable Using Ajax fails RRS feed

  • Question

  • User1349647816 posted

    Hi Guys, I have an ajax method that passes a value to a function in my controller, the function in my controller then takes the value that's passed to it and assigns that value to a private variable in the class, that part works fine however when I call another method from the same class class to access the value of the private variable the value always comes back as 0. Here's my code

    $.ajax({
    type: 'POST',
    dataType: "JSON",
    data: { mCount : number },
    url: '/mPost/mMethod'
    });

    and heres the code in my controller

    private int mCount { get; set; }

    public void mMethod(int number)
    {
    mCount = number ;
    }

    public void method2() {

    //Trying to access mCount from here always gives me 0

    }

    Tuesday, October 30, 2018 12:25 PM

All replies

  • User475983607 posted

    Hi Guys, I have an ajax method that passes a value to a function in my controller, the function in my controller then takes the value that's passed to it and assigns that value to a private variable in the class, that part works fine however when I call another method from the same class class to access the value of the private variable the value always comes back as 0. Here's my code

    $.ajax({
    type: 'POST',
    dataType: "JSON",
    data: { mCount : number },
    url: '/mPost/mMethod'
    });

    and heres the code in my controller

    private int mCount { get; set; }

    public void mMethod(int number)
    {
    mCount = number ;
    }

    public void method2() {

    //Trying to access mCount from here always gives me 0

    }

    Controllers exist only for the duration of the request.  A new request creates new controller and a new mCount.   That's why mCount is zero on the next request.

    State management is always a programming problem to solve in web development.  There are many ways to manage state in ASP.NET Core as illustrated in the fundamental docs; https://docs.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-2.1

    Tuesday, October 30, 2018 1:56 PM
  • User1520731567 posted

    Hi ShatterStar,

    I suggest you could change the type of mCount:

    private int mCount { get; set; }

    to:

    private static int mCount { get; set; }

    It will remember the result of the previous call assignment.

    Best Regards.

    Yuki Tao

    Wednesday, October 31, 2018 8:37 AM
  • User-474980206 posted
    Using a static will only work if the site only supports one user. As a static value is shared with all user requests.
    Wednesday, October 31, 2018 2:07 PM
  • User1349647816 posted

    Hi this worked but as Bruce said below this would present a problem when the website has multiple users.

    Thursday, November 1, 2018 7:38 AM