Miguel Rodrigo Albarracin Miguel Rodrigo Albarracin - 1 month ago 8
C# Question

Use an extension method in a Viewbag

I have the following extension method for DateTime type

public static class DateTimeHelper
{
public static DateTime ToCST(this DateTime dt)
{
TimeZoneInfo cstZone = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");
DateTime cstTime = TimeZoneInfo.ConvertTimeFromUtc(dt, cstZone);

return cstTime;
}
}


this works fine in the controller with DateTime objects, but in the view I want to use this in a ViewBag, just like this:

@ViewBag.PrioritySummary.UpdateDttm.ToCST();


I get the following error:

'System.DateTime' does not contain a definition for 'ToCST'
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'System.DateTime' does not contain a definition for 'ToCST'

Source Error:

Line 8: DateTime cstTime = TimeZoneInfo.ConvertTimeFromUtc(ViewBag.PrioritySummary.UpdateDttm, cstZone);
Line 9: }
Line 10: @ViewBag.PrioritySummary.UpdateDttm.ToCST();


How I could cast a ViewBag to DateTime, in order to apply the extension method, in the same line?


I tried:

@(DateTime)ViewBag.PrioritySummary.UpdateDttm.ToCST();


But this didn't work.

Answer

You should wrap your expression in parentheses:

@(((DateTime)ViewBag.PrioritySummary.UpdateDttm).ToCST());

and to add the corresponding using statement at the beginning of your view.

@using ...DateTimeHelper;
Comments