在我的控制器中我有这个:
ViewBag.lstIWantToSend= lstApps.Select(x => x.ID).ToList(); // creates a List<int> and is being populated correctly
我想将该列表传递给另一个控制器..所以在我看来我有:
@Html.ActionLink(count, "ActionName", new { lstApps = ViewBag.lstIWantToSend }, null)
控制器中的方法:
public ActionResult ActionName(List<int> lstApps) // lstApps is always null
有没有办法将一个int列表作为路由值发送到控制器方法?
答案 0 :(得分:3)
如果我有Json
List<int>
ViewBag.lstIWantToSend= new List<int> {1, 2, 3, 4};
所以我的观点会像
@Html.ActionLink(count, "ActionName", new { lstApps = Json.Encode(ViewBag.lstIWantToSend) }, null)
Json.Encode
会将List<int>
转换为json string
和ActionName
将是这样的
public ActionResult ActionName (string lstApps)
{
List<int> result = System.Web.Helpers.Json.Decode<List<int>>(lstApps);
return View();
}
Json.Decode<List<int>>
会将此json string
转换回List<int>
答案 1 :(得分:0)
MVC.net的约定是,您发送的所有内容都是单个模型。因此,如果您要发送对象列表(例如“人员列表”),则最好先在客户端到服务器之间以及从服务器到客户端对它们进行序列化。
在简单的事情上,例如@BryanLewis说的那样,您可以简单地自己用CSV序列化(字符串),然后将其拆分回接收的Action / Client。 对于更复杂的事情,您可以拥有(客户端)类似AngularJS及其出色的JSON.stringify(anyObject)/JSON.parse(anyString)的功能,并且(服务器端)可以拥有Newton.Soft出色的JsonConvert.Deserialize>(myJsonString)或JsonConvert.Serialize(someObject)。 json的优点在于它非常透明。
请记住-HTTP不喜欢对象。但是,来回传递字符串很棒。