How to read ViewData of type DateTime from controller in its razor view javascript function

Elena Rezaie 1 Reputation point
2021-07-30T11:33:52.707+00:00

I'm implementing asp.net core 3.1 project. In my controller method, I have a ViewData which is assigned by a value of type DateTime. Now in my razor view I need its value in a javascript function. I appreciate if anyone helps me regarding the issue.

What I have till now is using:

<script>
var datePart = @azzedinehtmlsql .Raw(ViewData["projectStartDate"]);
</script>

But it doesn’t work. I appreciate if anyone could solve my issue.

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,403 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Michael Taylor 51,346 Reputation points
    2021-07-30T15:24:16.277+00:00

    You are correct that you need to store the date into a JS variable. Something like this:

    <script>
    var datePart = '@ViewData["projectStartDate"]';
    </script>
    

    Of course I'm assuming that the ViewData value is already formatted into a string format that JS likes. If not then you'll need to do the conversion as part of the server-side logic in the script tag. The end result in JS would be something like this:

    <script>
    var datePart = '1/2/2021';
    </script>
    
    0 comments No comments

  2. Bruce (SqlWork.com) 61,731 Reputation points
    2021-07-31T22:43:38.923+00:00

    you don't specify the use of the date string. I assume you want to convert it to a javascript date. as suggested above:

    var datePart = '@ViewData["projectStartDate"]';

    fixes the syntax error, datePart is just a string. You can convert the string to a javascript date, but the success will depend on javascript version, as the formats don't always match. you use use iso date format:

    var datePart = new Date("@(((DateTime) ViewData["projectStartDate"]).ToString("o")))";

    note: if your daytime is UTC, then append z

    var datePart = new Date("@(((DateTime) ViewData["projectStartDate"]).ToString("o"))+"z")";

    0 comments No comments