formatting DateTime error “Templates can be used only with field access, property access, single-dimension array index..”

前端 未结 5 1108
被撕碎了的回忆
被撕碎了的回忆 2021-02-20 11:25

In MVC Razor view, I am trying to format a DateTime field to display time only. Using below code I am getting error \"Templates can be used only with field access, property acce

5条回答
  •  别那么骄傲
    2021-02-20 11:55

    Another possible approach could be using extension methods to achieve the same. Using that approach you will not be populating your views with hard coded format.

    Extension Method

        /// 
        /// Converts a DateTime string to Date string. Also if Date is default value i.e. 01/01/0001
        /// then returns String.Empty.
        /// 
        /// Input DateTime property 
        /// Pass true to show only date.
        /// False will keep the date as it is.
        /// 
        public static string ToString(this DateTime inputDate, bool showOnlyDate)
        {
            var resultDate = inputDate.ToString();
    
            if (showOnlyDate)
            {
                if (inputDate == DateTime.MinValue)
                {
                    resultDate = string.Empty;
                }
                else
                {
                    resultDate = inputDate.ToString("dd-MMM-yyyy");
                }
            }
            return resultDate;
        }
    

    View

     @Model.LastUpdateDate.ToString(true).
    

    Link: DateTime to Date in ASP.net MVC

提交回复
热议问题