Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Nick 95 posts 492 karma points
    May 17, 2024 @ 17:31
    Nick
    0

    System.InvalidCastException: Unable to cast object of type 'System.DateTime' to type 'System.String'

    Hi,

    I wondered if anybody could help me I am using Umbraco Cloud 11, and have a set of doc types to display a job vacancy like the below, What I would like is if the model value has data show the item, if not display none, the problem arises with the jobClosingDate item is null the whole page errors with this error:

    Unable to cast object of type 'System.DateTime' to type 'System.String'

    Any help would be much appreciated, thanks again to this great Umbraco community

    <ul class="job-meta">
                                @if (!String.IsNullOrEmpty((string)@Model.Value("jobLocation")))
                                {
                                <li>
                                     <i class="fas flaticon-location-pin"></i>Location:<span>@Model.Value("jobLocation")</span>
                                </li>
                                }
                                 @if (!String.IsNullOrEmpty((string)@Model.Value("salary")))
                                {
                                <li>
                                    <i class="fas fa-money-bill"></i>Salary:<span>@Model.Value("salary")</span>
                                </li>
                                }
                                @if (!String.IsNullOrEmpty((string)@Model.Value("jobClosingDate")))
                                {
                                <li>
                                    <i class="fas fa-calendar"></i>Closing Date:<span>@Model.JobClosingDate?.ToString("dd") @Model.JobClosingDate?.ToString("MMM")</span>
                                </li>
                                }
                            </ul>
    
  • Damian 69 posts 392 karma points
    May 22, 2024 @ 20:01
    Damian
    100

    Hi Nick, Looks like you're casting all your values before nullchecking:

      @if (!String.IsNullOrEmpty((string)@Model.Value("jobClosingDate")))
                                {
    

    check out this version where the cast is removed, it should check for null before you apply the ToString extension @Model.JobClosingDate?.ToString("dd") ::

      @if ( null != Model.Value("jobClosingDate"))
                                {
    

    hope this helps!

  • Nick 95 posts 492 karma points
    May 23, 2024 @ 18:50
    Nick
    0

    Many thanks Damien for your help, your solution worked perfectly,

    Thanks again

Please Sign in or register to post replies

Write your reply to:

Draft