Pass List<int> from actionlink to controller method

柔情痞子 提交于 2019-12-04 17:19:24

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>

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.

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