Search code examples
c#stringviewmodelstring-concatenationdata-masking

Mask string in ViewModel C#


I have a view that pulls a list of everything in the database and it works great. However there is one bit of information that I have to mask, and no matter what I try I can't seem to mask it.

I want to mask it with 5 * (no matter how long the string) and display the last 4 digits.

Any idea of the best way to accomplish this with what I have?

String example: "SD46346" && "ADFF3342422" && "56-AS4566S"

Controller

    vm.Accounts = accounts
        .Select(s => new AdminViewModel.Account
        {
            Id= (s._ID.Length > 40 ? Encryptor.Decrypt(s._ID) : s._ID),
        }).ToList();
    return View(vm);

ViewModel

public List<Account> Accounts { get; set;}

public class Account
{
    public string Id { get; set; }
}

Things I've tried : Server Error in '/xxxxx' Application. StartIndex cannot be less than zero. Parameter name: startIndex –

public string DisplayID
{
    get
    {
        return string.Format("*****{0}", Id.Substring(Id.Length - 4));
    }
} 

UPDATE

It wasn't my code, it was old data that was lost in the database that only had 2 characters.


Solution

  • If you're just after simple replacement for display, you could also add an extra property that you use for display purpose.

    string ID {get;set;}
    
    string DisplayID 
    {
        get
        {
            return string.Format("*****{0}", ID.substring(ID.Length - 4))
        }
    }