简体   繁体   中英

Pass list of object from View to controller using HttpPost

I am struggling a bit with passing list of object to C# code from view. If I pass a simple string it works fine. but its not working for List. So I am sure I am missing something 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 something here
    }

    //and return an integer
}

While debugging I can see that the @test variable is getting populated with the list of MyObject. But when I reach the code side its always null.

Please let me know if i am missing something here. Also tell me if more information is needed.

You're passing a C# object into a Javascript function. It doesn't know how to read that. You should serialize it into JSON before passing it in.

If you use Json.NET you can do it by

ViewBag.ObjectsList = JsonConvert.SerializeObject(yourlist);

Then you can continue as you were.

Some notes:

You should try to start using ViewModels instead of putting things in the ViewBag. On the Javascript side you should bind event handlers for things like clicking instead of using onclick as it would make your code much more manageable and reusable.

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