Search code examples
c#asp.net-mvcmodelgetter-setter

Model losing private field value for getter


I'm using ASP.Net MVC, and have a model that uses getters and setters to format a telephone number.

For some reason the getter always returns null, and checking when debugging shows that the private member is indeed null. This is despite the private member being successfully set to the formatted number when the model is populated.

The project is using entity framework and a dbInitializer that sets some test model properties (the project is still being developed), which I suppose may cause a problem, however the database is still being populated with the formatted number.

Below is my code for the model, can anyone see where I'm going wrong?

public class ContactDetails
{
    private string telephoneNumber;
    private string faxNumber;

    [DisplayName("Telephone number")]
    public string TelephoneNumber
    {
        get
        {
            return this.telephoneNumber;
        }
        set
        {
            // Format the telephone number
            // If not already formatted (doesn't have spaces)
            if (value.IndexOf(" ") < 0)
            {
                // Format a mobile number
                if (value.StartsWith("07"))
                {
                    this.telephoneNumber = value.Substring(0, 5) + " " + value.Substring(5, 3) + " " + value.Substring(8, 3);
                } else
                {
                    // Format a landline
                    this.telephoneNumber = value.Substring(0, 4) + " " + value.Substring(4, 3) + " " + value.Substring(7, 3);
                }                    
            }
        }
    }
    [DisplayName("Fax number")]
    public string FaxNumber { get; set; }
    [DisplayName("Email address")]
    public string EmailAddress { get; set; }
}

Solution

  • The problem you have is if your input value has no spaces, you never actually store it. Just add an else to the end:

    if (value.IndexOf(" ") < 0)
    {
        //snip                
    }
    else
    {
        this.telephoneNumber = value;
    }
    

    I would also recommend that you follow C# best practice by using _variableName for private variables:

    private string _telephoneNumber;
    private string _faxNumber;