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.
>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)
}