2012-07-20 25 views
0

我傳遞JSON參數到asp.net C#。並且該參數可以是單個或多個數據。Asp.net,C#,列表參數

所以我寫的參數爲LIST類類型的代碼。

但它返回一個錯誤,'對象引用未設置爲對象的實例'。

我寫這樣的測試代碼,它會產生相同的錯誤。

請查看我的代碼,並請指教我。

測試代碼,

在Controller類

[HttpGet] 
public ActionResult modelTest(TestList obj) 
{ 

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

和型號列表類,

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

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

,並呼籲/測試/ MODELTEST /?ID =身份識別碼&名=約翰& age = 11

然後,發生錯誤,

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: 

回答

3

wow名單可能永遠不會初始化。

你可以在TestList構造做(例如):

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 
} 

,或者如果你需要一個公共的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;} 
    } 
} 
+0

謝謝!現在錯誤消失了,但obj.wow.Count返回0.我預計1.你知道爲什麼嗎?我打電話給相同的網址 – 2012-07-20 14:03:27

+0

@Expertwannabe那麼,如果你想能夠將來自Querystring的集合綁定到你的wow List,你的querystring應該看起來像這樣:'/ Test/modelTest /?wow [0] .id = myId&wow [0] .name = john&wow [0] .age = 11' – 2012-07-20 14:24:55

+0

我看到了什麼問題。對不起,但你可以看看我之前發佈的問題。 http://stackoverflow.com/questions/11561550/asp-net-mvc3-c-figure-out-single-or-multiple-json-paramter再次感謝你! – 2012-07-20 14:38:49

0

我想你的呼叫系統是不正確的。你需要爲json數據添加「TestList」之類的列表。調試它並檢查「modelTest」方法實際收到的內容。