0

in my controller i'm trying to check if a datetime value is being passed through in a put request but when i don't send a value for that datetime field it will reset the value in the database to 01/01/0001/ here is the code in my controller how i check if its empty or not.( a little bit of it ) (Check user.Age!)

[HttpPut("User/Edit/{userid}")]
    public IActionResult Update(string token, int userid, [FromBody]User user)
    {


        bool RoleId = JWTValidator.RoleIDTokenValidation(token);
        var edit = _context.users.Find(userid);
        if (RoleId)
        {
            if (user.Name != null)
            {
                edit.Name = user.Name;
            }
            else
            {
                edit.Name = edit.Name;
            }
            if (user.LastName != null)
            {
                edit.LastName = user.LastName;
            }
            else
            {
                edit.LastName = edit.LastName;
            }
            if (user.Age != null)
            {
                edit.Age = user.Age;
            }
            else
            {
                edit.Age = edit.Age;
            }

so if the value is null it won't update but i guess if you don't enter anything it will see it as 01/01/0001 so i tried comparing to it like this

if(user.Age == "01/01/0001")

but i can't compare type datetime to a string. and also i'm using validation like this

if (ModelState.IsValid)
                {
                    _context.users.Update(edit);
                    _context.SaveChanges();
                }
                else
                {
                    return BadRequest(ModelState);
                }

and my model for Age is

[Display(Name = "Your Birthday")]
    [DataType(DataType.Date, ErrorMessage = "Not a correct date format, MM/DD/YYYY please.")]
    public DateTime Age { get; set; }

but if i send a put request with contents "Age": "test" it just gives me a 500 internal error instead of giving me the errormessage, am i handling that wrong?

Hope anyone could help me out.

Rajivrocks
  • 141
  • 2
  • 13
  • Use `DateTime.MinValue` instead of that string. – Nyerguds Dec 28 '18 at 17:33
  • Probably it helps to make the DateTime nullable as well. – David Walschots Dec 28 '18 at 17:59
  • 1
    You don't need those `else` statements where they set a property to it's own existing value... – Rufus L Dec 28 '18 at 18:22
  • You're really using `Age` to name a date/time value? Don't you think that's going to confuse people? When somebody asks your age, you don't say, "12/26/1999". You say, "I'm 19 years old." Please name the variable something like `BirthDate`. That'll be a log less confusing. – Jim Mischel Dec 28 '18 at 18:23
  • Yeah sorry, I was gonna do that but was first wanted to fix this problem @JimMischel – Rajivrocks Dec 28 '18 at 19:51
  • @RufusL yeah i realized, i'm taking them all out of all my Requests. Would this improve performance in anyway? theoretically i mean because this won't impact my performance a lot i assume but imagine if I had a huge site. – Rajivrocks Dec 28 '18 at 19:58
  • I doubt if it affected performance it would be enough to notice and possibly the compiler will optimize it away. But it's a lot of extra code to read. – Rufus L Dec 28 '18 at 20:15

4 Answers4

1

Well if you are looking for something to replace this if(user.Age == "01/01/0001")

Here you have a simple example: Returns 0 if is the same date

DateTime dt = DateTime.ParseExact("01/01/0001 00:00:00", "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture); //Use your default date string and your format type
DateTime dt2 = DateTime.Now;//Use Your Specific Date
var dtComp = DateTime.Compare(dt, dt2);
1

You could also declare age as nullable, i.e:

DateTime? user.Age  = new DateTime();

You can then easily check for null an also simply set edit.Age like this(if you want a default value):

edit.Age = user.Age ?? new DateTime(1970,01,01);

regards.

1
DateTime  myDate;
if(myDate.Date == DateTime.MinValue)
{
    //Do!
}
Dubakus
  • 11
  • 1
0

It sounds like the problem here is that you need to compare a struct to its default value, which is not null. To do this, you can simply use the default keyword to get the default value for the type. Note that you can do this with classes as well as structs:

if (user.Age != default(DateTime))
{
    edit.Age = user.Age;
}
Rufus L
  • 36,127
  • 5
  • 30
  • 43
  • Oh, I did like Nyer said and used DateTime.MinValue and it worked perfectly. but I'll try this a swell – Rajivrocks Dec 28 '18 at 19:53
  • Cool, that make sense. `MinValue` happens to be the default for `DateTime`, but this option makes it so you don't have to know that, and you can use it with any type, for example: `if (user.LastName != default(string))` – Rufus L Dec 28 '18 at 20:10
  • But then i have another question that i asked in this post, Why does it return a 500 server error when i input a wrong format for type datetime, for example "Birthday": "test" changed Age to Birthday btw. check the original post for validation statement and model for Birthday – Rajivrocks Dec 28 '18 at 20:40
  • Look through the answers to [this question](https://stackoverflow.com/questions/5212248/get-error-message-if-modelstate-isvalid-fails) for some ideas on how to display the error message. – Rufus L Dec 28 '18 at 20:49