在MVC4视图中转换datetime会导致错误

时间:2014-04-04 21:12:32

标签: c# asp.net-mvc asp.net-mvc-4 datetime

我的项目中有一个内容实体模型,我是由EF6创建的。

 public partial class Content
{
    public Content()
    {
        this.Comments = new HashSet<Comment>();
    }

    public int Id { get; set; }
    public string Subject { get; set; }
    [DataType(DataType.MultilineText)]
    public string Brief { get; set; }
    [UIHint("tinymce_full"), AllowHtml]
    public string MainText { get; set; }
    [DataType(DataType.DateTime)]
    public System.DateTime DateOfPublish { get; set; }
    [DataType(DataType.ImageUrl)]
    public string SmallImageUrl { get; set; }
    [DataType(DataType.ImageUrl)]
    public string BigImageUrl { get; set; }
    public string KeyWords { get; set; }
    [DataType(DataType.DateTime)]
    public System.DateTime DateOfExpire { get; set; }
    public string AutherUserName { get; set; }
    public long VisitVCount { get; set; }
    public string Visible { get; set; }
    public int ContentGroupId { get; set; }
    public long LikeCount { get; set; }

    public virtual ContentGroup ContentGroup { get; set; }
    public virtual ICollection<Comment> Comments { get; set; }
}

如您所见,我有一列 DateOfPublish ,其类型为日期时间

我想使用此功能将日期 DateOfPublish 转换为波斯日期:

public string ConvertToPersianToShow(DateTime? datetime)
        {
            string date;
            DateTime dt;

            if (!datetime.HasValue) return "";
            dt = datetime.Value;          
            string year = Convert.ToString(persian_date.GetYear(dt));
            string month = Convert.ToString(persian_date.GetMonth(dt));
            string day = Convert.ToString(persian_date.GetDayOfMonth(dt));
            if (month.Length == 1)
            {
                month = "0" + Convert.ToString(persian_date.GetMonth(dt));
            }
            if (day.Length == 1)
            {
                day = "0" + Convert.ToString(persian_date.GetDayOfMonth(dt));
            }
 Convert.ToString(persian_date.GetMonth(dt)) + "/" +

            date = year + "/" + month + "/" + day;
            return date;
        }

所以我在我的视图(内容视图)中调用此函数,所以我尝试使用此函数在波斯语中显示日期。所以我将英语日期传递给我的函数,如下所示:

@{
    ViewBag.Title = "Index";
    DateConverter objconverter = new DateConverter();
}
         <td>
            @Html.DisplayFor(objconverter.ConvertToPersianToShow(modelItem => item.DateOfPublish ))
    </td>

但我收到了这个错误:

Argument type "lambda expression" is not assignable to parameter type 'system.nullable<system.datatime>'

祝你好运

2 个答案:

答案 0 :(得分:1)

  @Html.DisplayFor(modelItem => objconverter.ConvertToPersianToShow(item.DateOfPublish ))

答案 1 :(得分:0)

我想你想要:

@Html.DisplayFor(item => objconverter.ConvertToPersianToShow(item.DateOfPublish ))