Pass List<int> from actionlink to controller method

可紊 提交于 2019-12-06 11:11:08

问题


In my controller I have this:

ViewBag.lstIWantToSend= lstApps.Select(x => x.ID).ToList();  // creates a List<int> and is being populated correctly

I want to pass that list to another controller.. so in my view I have:

@Html.ActionLink(count, "ActionName", new { lstApps = ViewBag.lstIWantToSend }, null)

Method in Controller:

public ActionResult ActionName(List<int> lstApps)   // lstApps is always null

Is there a way to send a list of ints as a route value to a controller method?


回答1:


its not possible directly but you can do it with Json if i have List<int>

ViewBag.lstIWantToSend= new List<int> {1, 2, 3, 4};

so my view would be something like

@Html.ActionLink(count, "ActionName", new { lstApps = Json.Encode(ViewBag.lstIWantToSend) }, null)

Json.Encode will convert List<int> to json string

and ActionName will be like this

 public ActionResult ActionName (string lstApps)
        {
            List<int> result = System.Web.Helpers.Json.Decode<List<int>>(lstApps);

            return View();

        }

Json.Decode<List<int>> will convert this json string back to List<int>




回答2:


MVC.net works on the convention that everything you send is a single Model. So if you want to send a list of objects (say a List of Persons) - it might be a good idea to serialize them first both from client to server, and from server to client.

On simple things, like @BryanLewis said, you can simply serialize it yourself with CSV (to string), and then split it back on the recieving Action/Client. For more complex things you have (client side) things like AngularJS with its excelent JSON.stringify(anyObject)/JSON.parse(anyString) and you have (server side) Newton.Soft 's excelent JsonConvert.Deserialize>(myJsonString) or JsonConvert.Serialize(someObject). The nice thing about json is that it's very transparent.

Bear in mind - HTTP does not like objects. But it's great with passing strings back and forth.



来源:https://stackoverflow.com/questions/42816493/pass-listint-from-actionlink-to-controller-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!