How to split string in View in MVC?

29,597

Solution 1

you can do it like this:

@{

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

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

    }

}

or if "." will be only one time in that string then you can hardcode like this:

@{

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

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

        }
}

Solution 2

see below example , which finds last word of a string after last dot in it.

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
}

here last comes as xyz

Share:
29,597
geekforfreek
Author by

geekforfreek

Updated on July 17, 2020

Comments

  • geekforfreek
    geekforfreek almost 4 years

    In my View I have this condition:

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

    How can I split this string "User.Identity.Name" in View (in MVC) so I can create new condition, something like this:

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

    thanks.

  • geekforfreek
    geekforfreek almost 10 years
    this is great Ehsan, but how to implement this in View?
  • Ehsan Sajjad
    Ehsan Sajjad almost 10 years
    simple the way you do in action same way in view
  • Ehsan Sajjad
    Ehsan Sajjad almost 10 years
    you just need to create razor block to write c# code like @{ write statements here }