0

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.

1
  • Please note that the model-view-controller tag is for questions about the pattern. There is a specific tag for the ASP.NET-MVC implementation. Commented Jul 28, 2016 at 11:26

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I am new to MVC and I am editing an existing code. Also, even I don't like to add things to ViewBag. if I add it to model do I still need to use Json.NET?
@Newbee Ultimately yes. Before you can use it in Javascript you need to serialize it into Json. Where and how you do that is up to you depending on your needs.
I finally managed to sort this. I am using JavaScriptSerializer though. Thanks for help. Rather than passing the whole object list I am breaking it into a Dictionary with necessary data and serializing that variable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.