简体   繁体   English

需要ASP.NET MVC5日期时间吗?

[英]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. 当PostPosted变量保存正确的时间时,这工作得很好。

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. 我发现这很奇怪,因为我没有使用[Required]属性。

I'm aware not I can use the nullable DateTime? 我知道我不能使用可为空的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. 如何使用户不能输入DateTime,但这也意味着我在数据库中最终为null,但是我希望DateTime自动设置为发布时间。

All value types (including DateTime ) when posted back to the MVC controller, should have a value. 当所有值类型(包括DateTime )回发到MVC控制器时,都应具有一个值。

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: 在您的<form>元素中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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