question

ElenaRezaie-7854 avatar image
0 Votes"
ElenaRezaie-7854 asked Bruce-SqlWork answered

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

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 = @Html.Raw(ViewData["projectStartDate"]);
</script>

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


dotnet-aspnet-core-mvc
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Bruce-SqlWork avatar image
0 Votes"
Bruce-SqlWork answered

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")";

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

cooldadtx avatar image
0 Votes"
cooldadtx answered

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>

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.