Add one day to a model's data

℡╲_俬逩灬. 提交于 2020-01-05 05:51:14

问题


I am new to Razor and I want to know how to add one day to model's date object. I need to put a "next day" link

Here is the view code

<a href="@Html.DisplayNameFor(model => model.date)">Next Day</a>

回答1:


You can pass the NextDay as a DateTime in the Model as well using DateTime.AddDays() method. This method returns a new DateTime that adds the specified number of days to the value of this instance.

model.NextDay = startDate.AddDays(1);

then use that property in your DisplayNameFor:

<a href="@Html.DisplayNameFor(model => model.NextDay)">Next Day</a>

There is a little paragraph about it on MSDN

This method does not change the value of this DateTime. Instead, it returns a new DateTime whose value is the result of this operation.




回答2:


You generally don't want to "calculate" values in your view - that's the model's responsibility. The cleanest way is to add a property to your model that calculates the next date:

public DateTime NextDay 
{
    get {return this.date.AddDays(1); }
}

then use that property in your DisplayNameFor:

<a href="@Html.DisplayNameFor(model => model.NextDay)">Next Day</a>



回答3:


Is model.date a DateTime? If so then use DateTime.AddDays. It might not be worth adding a special property to your model just for this.

Also, are you sure that your date is going to be serialized in a format your server will understand? I would recommend ensuring you specify a particular format for dates to be used in Urls, such as yyyy-MM-dd, using the ToString() method of the DateTime object. This way any changes to your server locale will not impact your site.

<a href='@Html.DisplayNameFor(model => model.Date.AddDays(-1).ToString("yyyy-MM-dd"))'>Previous Day</a>
<a href='@Html.DisplayNameFor(model => model.Date.AddDays(1).ToString("yyyy-MM-dd"))'>Next Day</a>


来源:https://stackoverflow.com/questions/17030575/add-one-day-to-a-models-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!