Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# trim within the get; set;

I am total MVC newbie coming from 10 years of webforms. Here is the code I have inherited:

namespace sample.Models
{
    public class Pages
    {
        public int PageID { get; set; }
        public string FolderName { get; set; }
    }
}

How can I apply a trim function to the "set" portion of this code? Right now it is allowing spaces at the end of foldername and I need to prevent that.

Okay I have incorporated the suggestions however the spaces are still getting saved.
Here are the UI/ vs Database. The UI is trimming properly but the full value with spaces is stored in the table:

UI

Database has spaces

like image 898
user2055729 Avatar asked Dec 28 '16 19:12

user2055729


2 Answers

You need a backing field:

public class Pages
{
    public int PageID { get; set; }

    private string _folderName;
    public string FolderName 
    { 
        get { return _folderName; } 
        set { _folderName = value.Trim(); }
    }
}

In the setter method we use the Trim string's method, which

Removes all leading and trailing white-space characters from the current String object.

For further info regarding this method, please have a look here.

like image 83
Christos Avatar answered Sep 25 '22 07:09

Christos


What about this solution:

    public class Pages
    {
         private string _folderName;

         public int PageID { get; set; }

         public string FolderName
         {
              get { return _folderName; }
              set { _folderName = value?.Trim() ?? string.Empty; }
         }
}
like image 20
MagicUser123 Avatar answered Sep 22 '22 07:09

MagicUser123