开发者

Passing a list of object from a view to the controller in asp.net mvc?

开发者 https://www.devze.com 2022-12-24 14:03 出处:网络
Is this possible? What I want to do is pass a list of objects as a paramter in an actionlink At the moment when I try to do this the list is always empty by the time it reaches the controller!

Is this possible?

What I want to do is pass a list of objects as a paramter in an actionlink

At the moment when I try to do this the list is always empty by the time it reaches the controller!

In the view

 <%= Url.Action("ActionName", new { list = Model.ListOfObjects}) %>

In the controller

public ActionResult ActionName(List<Object&开发者_Python百科gt; list)
    {
        //Do stuff
    }


In terms of whether or not it's possible - it's possible, but not in the way you're trying. Keep in mind that this will translate to a URL which will get parsed by MVC and the different parameters will get passed to the action either as direct parameters or through a model binder.

I would recommend that you try to figure out what the URL will have to look like and then maybe do some custom code to generate the URL (maybe use a custom helper function/extension method). If you combine this with a custom model binder you should have a pretty elegant solution which does exactly what you want.

For example, if your list has 3 objects of type string you could write a helper to generate a url like this (let's say the list contains 'first', 'second', and 'third')

/Controller/Action?obj1=first&obj2=second&obj3=third

Now you simply need to write a model binder that looks for entries called 'obj1','obj2', etc and simply add the results into a list.


While it may take the list of objects, it probably won't render what you are expecting to see; it may actually suck in the values of the list class (or whatever class this list represents) and use that as the params.

Not through a get request, unless you write out the params manually and deserialize the params too. Or, instead, do a postback to the server with these values within the form; then, this would populate correctly.

HTH.


Something like this would work, I suggest making a helper to contain this logic if you need it in a lot of places.

<% var values = new RouteValueDictionary();
   for (int i = 0; i < Model.ListOfObjects.Count -1; i++)
   {
      values.Add("list["+i+"]", Model.ListOfObjects[i]);
   }%>
<%= Url.Action("ActionName", values); %>

The action will know how to handle the list in the controller.

0

精彩评论

暂无评论...
验证码 换一张
取 消