List< string>传递给ViewBag的文件被"System.Collections.Generic.List`1 [System.String]"破坏了; [英] List<string> passed in ViewBag gets spoiled with "System.Collections.Generic.List`1[System.String]"

查看:152
本文介绍了List< string>传递给ViewBag的文件被"System.Collections.Generic.List`1 [System.String]"破坏了;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想我有一个很白痴的问题,但这是:

I think I have a very noob question but there it is:

我有一个指向另一个控制器的链接,我想传递一个字符串列表.

I have a link to another controller and I want to pass a list of strings.

控制器:

[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" })

在我的控制器中,正确创建了ViewBag.ReasonGroupName:一个索引为0的项([0])的字符串为"Faults"的列表,但是当我在另一个控制器中收到该列表时,列表的0索引元素随之出现"System.Collections.Generic.List1[System.String]"代替"Faults"

In my controller the ViewBag.ReasonGroupName is created properly: a list with the index 0 item ([0]) with the string "Faults"but when I receive it in my other controller the 0 index element of my list comes with "System.Collections.Generic.List1[System.String]" instead of "Faults"

我还尝试将ViewBag更改为ViewData对象,但出现相同的问题.

I also try changing ViewBag for ViewData object but same problem appear.

我对自己做错的任何想法吗?

Any ideia on what I'm doing wrong?

谢谢

推荐答案

如果在List类型的实例上调用ToString(),则会得到文本"System.Collections.Generic.List1 [System.String]". .生成链接时,URL必须是一个字符串,因此将在每个参数上调用ToString().

The text "System.Collections.Generic.List1[System.String]" is what you get if you call ToString() on an instance of the List type. When you generate the link the url has to be a string, hence ToString() is called on each argument.

不清楚您要通过操作链接发送哪些信息.如果您想要第一个值,则可以将链接更改为以下内容:

It is not clear what information you are trying to send via the action link. If you want the first value then you could change the link to be the following:

@Html.ActionLink(item.username, "Edit", "Hours", new { IdUser = item.IdUser, ReasonGroupNames = ((List<string>)ViewBag.ReasonGroupName)[0] }, new { @class = "iframeFull" })

这会将ReasonGroupName设置为列表中的第一个值.

This will set the ReasonGroupName to the first value in the list.

但是您可能希望发送列表中的所有值,而不仅仅是第一个.在这种情况下,您可以将列表的所有值连接到字符串中,然后将其作为参数传递.

But you probably want to send all the values in the list and not just the first. In that case you could join all the values of the list into a string and pass that as the argument instead.

因此,您可以在控制器中执行以下操作:

So in your controller you could do:

ViewBag.ReasonGroupName = string.Join(",", yourListVariableHere);

这会将列表转换成逗号分隔的字符串,该字符串可以正确包含在url中.

This will convert the list into a comma separated string that can be included in the url properly.

这篇关于List&lt; string&gt;传递给ViewBag的文件被"System.Collections.Generic.List`1 [System.String]"破坏了;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆