MVC helper class parameter issue

2019-09-02 11:33发布

i have an issue in passing parameter to helper class

My model

public DateTime? dTime { get; set; }

Helper class as answered by Darin Dimitrov

public static IHtmlString MyFunction(this HtmlHelper html, DateTime value)
        {
            return new HtmlString(value.ToString("dd/MM/yyyy"));
        }

and am accessing in myview to convert datetime

foreach (var item in Model.lstCommet)
{
 <div class="comment_time">@Html.MyFunction(item.dTime)</div>
 }

but am getting "ASP.DetailPageHelper.convertTime(System.DateTime)' has some invalid arguments"

what i am doing wrong ?

1条回答
太酷不给撩
2楼-- · 2019-09-02 12:01

Because it's a nullable type you need to reference the value.

foreach (var item in Model.lstCommet)
{
   <div class="comment_time">@Html.MyFunction(item.dTime.Value)</div>
}

You might want to run a null check as well.

foreach (var item in Model.lstCommet)
{
   if(item.dTime.HasValue)
   {
       <div class="comment_time">@Html.MyFunction(item.dTime.Value)</div>
   }
}
查看更多
登录 后发表回答