Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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)
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading