我想我有一个非常菜鸟的问题,但事实是:
我有一个到另一个 Controller 的链接,我想传递一个字符串列表。
Controller :
[HttpPost]
public ActionResult Index(DateTime? dateFilter, int? Provider, int? middleOffice)
{
...
ViewBag.ReasonGroupName = new List<string>() { "Faults" };
...
}
查看:
@Html.ActionLink(item.username, "Edit", "Hours", new { IdUser = item.IdUser, ReasonGroupNames = (List<string>)ViewBag.ReasonGroupName }, new { @class = "iframeFull" })
在我的 Controller 中,ViewBag.ReasonGroupName
已正确创建:一个索引为 0 的项目 ([0]) 的列表,其中包含字符串 “Faults”
,但是当我收到在我的另一个 Controller 中,我的列表的 0 索引元素带有 "System.Collections.Generic.List1[System.String]"
而不是 "Faults"
我也尝试更改 ViewBag
为 ViewData
对象,但出现了同样的问题。
关于我做错了什么有什么想法吗?
谢谢
最佳答案
如果在 List 类型的实例上调用 ToString(),则会得到文本“System.Collections.Generic.List1[System.String]”。生成链接时,url 必须是字符串,因此每个参数都会调用 ToString()。
尚不清楚您尝试通过操作链接发送什么信息。如果您想要第一个值,则可以将链接更改为以下内容:
@Html.ActionLink(item.username, "Edit", "Hours", new { IdUser = item.IdUser, ReasonGroupNames = ((List<string>)ViewBag.ReasonGroupName)[0] }, new { @class = "iframeFull" })
这会将 ReasonGroupName
设置为列表中的第一个值。
但是您可能想要发送列表中的所有值,而不仅仅是第一个值。在这种情况下,您可以将列表中的所有值连接到一个字符串中,并将其作为参数传递。
所以在你的 Controller 中你可以这样做:
ViewBag.ReasonGroupName = string.Join(",", yourListVariableHere);
这会将列表转换为可以正确包含在 url 中的逗号分隔字符串。
关于c# - ViewBag 中传递的 List<string> 被 "System.Collections.Generic.List` 1[System.String] 破坏”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17469697/