MVC helper class parameter issue

2019-09-02 11:37发布

问题:

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:

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>
   }
}