【问题标题】:How to split string in View in MVC?如何在 MVC 的视图中拆分字符串?
【发布时间】:2014-07-29 16:08:58
【问题描述】:

在我看来,我有这种情况:

@if (User.Identity.Name == "abc")
{
   ... do this!
}

如何在视图(在 MVC 中)中拆分此字符串“User.Identity.Name”,以便创建新条件,如下所示:

string last = User.Identity.Name.Substring(User.Identity.Name.LastIndexOf('.') + 1);
if (last == "this")
{
   ... do this!
}

谢谢。

【问题讨论】:

  • 你可以使用Split("some string")分割它
  • 我需要找到点“。”和字符串的最后一个索引,所以我需要在点之后找到字符串

标签: asp.net-mvc string model-view-controller view split


【解决方案1】:

你可以这样做:

@{

    var temp= User.Identity.Name.Split('.');

    if (temp[temp.Count() - 1] == "this")
    {

    }

}

或者如果 "." 在该字符串中只有一次,那么您可以像这样进行硬编码:

@{

    var temp= User.Identity.Name.Split('.');

        if (temp[1] == "this")
        {

        }
}

【讨论】:

  • 这很好 Ehsan,但是如何在 View 中实现呢?
  • 在视图中以相同的方式简化您的操作方式
  • 你只需要创建剃须刀块来编写像@{ write statements here }这样的c#代码
【解决方案2】:

见下面的例子,它在字符串的最后一个点之后查找字符串的最后一个单词。

String str = "abc.def.xyz";

String last = str.substring(str.lastIndexOf('.')+1);
System.out.println(last);
if(last.equals("something")){
    //do this
}

else{
    //do this
}

这里lastxyz

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-24
    • 1970-01-01
    • 2021-10-14
    • 2013-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多