c# - Pass list of object from View to controller using HttpPost -


i struggling bit passing list of object c# code view. if pass simple string works fine. not working list. sure missing here.

view

<div class="row control-actions"> @{     list<myobject> test = viewbag.objectslist;     <button type="button" class="btn btn-primary btn-wide" onclick="addallobjectstoexp('@test')">add all</button>             } </div>  <script type="text/javascript">  function addallobjectstoexp(objlist) {     $.post('@url.action("addallobjectstoexp", "exportobjects")', { objectslist: objlist},     function (result) {         $('#numbers').html(result);     }); } </script> 

code

[httppost] [outputcache(location = system.web.ui.outputcachelocation.none, nostore = false, duration = 0)] public int addallobjectstoexp(list<myobject> objectslist) {     foreach(myobject obj in objectlist)     {         //do here     }      //and return integer } 

while debugging can see @test variable getting populated list of myobject. when reach code side null.

please let me know if missing here. tell me if more information needed.

you're passing c# object javascript function. doesn't know how read that. should serialize json before passing in.

if use json.net can by

viewbag.objectslist = jsonconvert.serializeobject(yourlist); 

then can continue were.

some notes:

you should try start using viewmodels instead of putting things in viewbag. on javascript side should bind event handlers things clicking instead of using onclick make code more manageable , reusable.


Comments

Popular posts from this blog

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -