sptramp
sptramp

Reputation: 946

Update property values using the ViewModel

The ViewModel below is used on multiple forms.

My goal is to update values received from those forms using the DateRangeViewModel itself. Is it possible?

Example: User submits "2022-01-01 12:00:00 AM" and I update it to "2022-01-02 12:00:00 AM" before passing it to the controller.

What I have tried:

public class DateRangeViewModel
{
    public DateTime? From { get; set; }
    public DateTime? To { 
        get 
        {
            if (!To.HasValue) { return null; }
            return To.Value.AddDays(1);
        }
        set {}
    }
}

And it throws an Exception of type 'System.StackOverflowException'.

I know I can update these values through the controller. However, it is not my intent.

Upvotes: 0

Views: 90

Answers (2)

riffnl
riffnl

Reputation: 3183

You're basically creating a recursive function here (hence the StackOverflowException). You don't need to reference "To" inside the getter, you need to reference "an internal value" (most likely private).

So this should work:

private DateTime? ToValue { get; set; }
public DateTime? To 
{
    get { return ToValue.HasValue ? ToValue.AddDays(1) : null; }
    set { ToValue = value; }
}

Upvotes: 2

Christian Gollhardt
Christian Gollhardt

Reputation: 17034

Use a backing field:

public class DateRangeViewModel
{   
    public DateTime? From { get; set; }
    public DateTime? To { 
        get 
        {
            return _to;
        }
        set
        {
            if (value == null)
            {
                _to = null;
            }
            else
            {
                _to = value.Value.AddDays(1);
            }
        }
    }

    private DateTime? _to;
}

Probably it would be clearer, if you use an additional Property:

public class DateRangeViewModel
{   
    public DateTime? From { get; set; }
    public DateTime? To { get; set; }
    public DateTime? ToPlus1Day => To == null ? null : To.Value.AddDays(1)
}

Upvotes: 1

Related Questions