如何在ASP.NET MVC4中拆分单词?

时间:2013-05-19 11:44:37

标签: c# asp.net-mvc

如何在ASP.NET MVC4中拆分单词?

到目前为止,这是我的尝试。

public ActionResult Index()
        {
            var aaa = System.Text.RegularExpressions.Regex.Split("12:::34:::55", ":::");

            ViewBag.test = aaa;
            return View();
        }

但页面显示System.String[]

5 个答案:

答案 0 :(得分:2)

在您的视图中迭代ViewBag.test

答案 1 :(得分:1)

这会拆分你的字符串并返回一个数组:

public ActionResult Index()
{
    string[] elements = string.Split("12:::34:::55", ":::");

    ViewBag.test = elements;
    return View();
}

修改

以下是迭代视图中元素的方法:

@foreach (string element in ViewBag.test)
{
    <span>@element</span>
    // or other things ...
}

答案 2 :(得分:1)

您正在看到数组的string表示。

要显示元素,请使用string.Join

ViewBag.test = string.Join(",", //insert separator here
                           aaa);

这将返回"12,34,55"

如果您想要单独的行,请将","替换为Environment.NewLine。您还可以使用" "或您选择的任何其他分隔符。

答案 3 :(得分:0)

在您的视图中,您应该遍历值:

@foreach (string item in ViewBag.test)
{
    <p>@item</p>
}

答案 4 :(得分:-1)

你刚刚使用Split("x:::y:::z",":::"),在这种情况下,它会返回字符串数组,因此它会显示消息System.String[]

如果你想在一个字符串数组中将其提及为

string s = "x:::y:::z";
string[] Splittedwords=s.Split(new string[] { ":::" }, System.StringSplitOptions.None);

否则,如果你只想要第一个,你可以使用

var x = s.Split(new string[] { ":::" }, System.StringSplitOptions.None)[0];

此处[0]表示第一个拆分为您提供x,[1]为您提供y。

现在您可以将ViewBag.test = Splittedwords;传递给视图 否则ViewBag.test = x;传递单个字符。

注意:请记住在View中你必须执行类型转换,否则你将继续得到相同的错误