简体   繁体   中英

ASP.NET MVC5 Datetime required?

I'm try to work on a comment section and i've made it so a user can post a comment, but I also want a time stamp. So this is how my model looks like

    public class Suggestion
{
    public int Id { get; set; }

    [Required]
    [Display(Name = "Suggestion")]
    public string Comment { get; set; }

    public DateTime WhenPosted { get; set; }

    public Suggestion()
    {
        WhenPosted = DateTime.Now;
    }
}

How ever doing this will end up with the user having to enter the date him self which removes the point of having it.

So I made a constructor that looks like this:

public Suggestion()
    {
        WhenPosted = DateTime.Now;
    }

Which works just fine the WhenPosted variable holds the right Time.

How ever when a user is going to post his comment it tells me this: The WhenPosted field is required.

Which I find rather weird as I do not use the [Required] attribute.

I'm aware not I can use the nullable DateTime? How ever that allows my user to not enter a DateTime but it also means my ends up null in my database, but I want the DateTime to be automaticly set to the time it was posted.

All value types (including DateTime ) when posted back to the MVC controller, should have a value.

To achieve the needs as per your requirement, I would probably do something like

        private DateTime _date;    

        public DateTime Date
        {
            get {
                // by default the date was getting set to 1/1/0001 12:00:00 AM
                if (_date == null || _date.ToString() == "1/1/0001 12:00:00 AM")
                {
                    return _date = DateTime.Now;
                }    
                return _date; 
            }
            set {

                _date = value; 
            }
        }

If you just assign a default value to the property it should work fine.

private DateTime _date = DateTime.Now;    //default value assigned here.
public DateTime Date {
    get { return _date; }
    set { _date = value; }
}

Another method, if you want to use the code in your question, would be to round-trip the property value.

Within your <form> element:

@Html.HiddenFor(m => m. WhenPosted)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM