user1114522
user1114522

Reputation: 11

C# class null reference

I'm using Ajax to bring back values from the server, but when calling the method incrementvalue(), _value has a null reference even though it is set up previously in the intialisevalue() method. I have some example code below.

public class test
{
    public int value;

    public void increment(int _value)
    {
        value = value + _value;
    }

    public void setvalue(int _value)
    {
        value = _value;
    }
}

public test _value;

public JsonResult intialisevalue()
{
    _value = new test();
    _value.setvalue(9);

    return Json(_value);
}

public JsonResult incrementvalue()
{
    _value.increment(2);
    return Json(_value);
}

Any ideas?

Upvotes: 1

Views: 159

Answers (4)

Jason Meckley
Jason Meckley

Reputation: 7591

controllers only exist within the request. after the response is sent the controller is disposed. thus, test no longer exists. you need to pass the test object into the controller

public JsonResult incrementvalue(test t, increment i)
{
      t.increment(i);
      return Json(t);
}

Upvotes: 1

David Spence
David Spence

Reputation: 8079

You need yo re-initialize _value each call to the server. HTTP is stateless, your variables do not keep their state between requests.

Upvotes: 0

Lion
Lion

Reputation: 19027

You're not assigning a new reference to _value in the following method.

public JsonResult incrementvalue()
{
    _value.increment(2);
    return Json(_value);
}

you should modify it as follows.

public JsonResult incrementvalue()
{
    _value=new Test();   //Assigns a new reference to `_value`
    _value.increment(2);
    return Json(_value);
}

Upvotes: 0

tbddeveloper
tbddeveloper

Reputation: 2447

Your value is not retained between calls to the controller. When you call the incrementvalue method, it's working with a new copy of that field. You'll probably find that it's throwing an exception because _value is null.

You should pass the copy of value into the incrementvalue method when you call the controller, then increment that and return it again.

Upvotes: 0

Related Questions