-1

I have properties defined in my view model like so -

public string FullName
        {
            get { return FirstName + " " + LastName; }
            set {
                    FirstName = FullName.Split(null)[0];
                    LastName = FullName.Split(null)[1];
                }
        }


        public string FirstName { get; set; }


        public string LastName { get; set; }

My Razor View has this -

<label for="FullName">Name</label>
            @Html.TextBox("FullName", Model.FullName)  

While I am able to set the full name and display it in the text box when the page loads, I am NOT able to retrieve the value while form is submitted.

I need to retrieve the value from this text box too when the value is changed. What am I doing wrong here?

GilliVilla
  • 4,998
  • 11
  • 55
  • 96
  • 1
    Either make FullName the property and First and Last methods that parse FullName or make FullName a method, which you could not use in your razor view that combines First and Last. Doing what you are doing in the Setter of FullName is bad. – Craig Selbert Feb 14 '17 at 20:51
  • 1
    Should `FullName` even have a `set;` property? – Mark C. Feb 14 '17 at 20:51
  • In your setter you try to set `FirstName` and `LastName` properties to the value of `FullName` which in turn calls the getter which return the values of `FirstName` and `LastName` which are `null` because they have not been set. –  Feb 14 '17 at 21:00

1 Answers1

0

It depends on what you're wanting to do here..

If you want to be able to "set" the FullName property and just split the string into chunks and assign those values to FirstName and LastName, you'd do it like this (and not use the property's name in itself):

        public string FullName
        {
            get { return FirstName + " " + LastName; }
            set
            {
                this.FirstName = value.Split(null)[0];
                this.LastName = value.Split(null)[1];
            }
        }

The issue in your code is that you're trying to use the FullName setter as a constructor, when in reality the First and LastName properties should be set individually and the FullName should just have a get; property just like you have (in my opinion).

Mark C.
  • 6,332
  • 4
  • 35
  • 71