简体   繁体   中英

Asp.net, C#, List parameter

I'm passing JSON parameter to asp.net C#. and the parameter could be single or multiple data.

so I write the code that takes parameter as LIST class type.

but It return an error, 'Object reference not set to an instance of an object.'

I write test code like this, and it makes same error.

please review my code, and please advice me.

Test Code,

In Controller class

[HttpGet]
public ActionResult modelTest(TestList obj)
{

    return Content(obj.wow.Count.ToString());
}

and model and list class,

public class TestList
{
    public List<TestModel> wow { get; set; }
}

public class TestModel
{
    public string id { get; set; }
    public string name { get; set; }
}

and call /Test/modelTest/?id=myId&name=john&age=11

then, Error occur,

Object reference not set to an instance of an object.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error: 


Line 338:        {
Line 339:            
Line 340:            return Content(obj.wow.Count.ToString());
Line 341:        }
Line 342:

The wow list is probably never initialized.

You can do it (for example) in the TestList constructor :

public class TestList
{
   public TestList() {
      wow = new List<TestModel>();
   }
    public List<TestModel> wow { get; private set; }//if you do this way, you can have a private setter
}

or if you need a public setter

public class TestList {

    private List<TestModel> wow_;

    public List<TestModel> wow {
       get {
          if (wow_ == null) wow_ = new List<TestModel>();
          return wow_;
       }
       set {wow_ = value;}
    }
 }

I think your calling system is not right. you need to add "TestList" like list for json data. Debug it and check that what is actually received by the "modelTest" method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM