Question: Cannot get DateTime.Now as string in Razor View

Question

Cannot get DateTime.Now as string in Razor View

Answers 2
Added at 2016-12-24 10:12
Tags
Question

I want to get current time in a Razor View and use it in Javascript as shown below:

@{ 
    string fileName = "Score_List_" + DateTime.Now.ToShortDateString();
}


<script>
    // assign C# variable to JavaScript variable.
    var FileName = @Html.Raw(@fileName);
</script>

And then I should be able to use it in a Javascript call as shown below:

...
{
    extend: 'excelHtml5',
    text: FileName,
    title:'List', //title & file name
}
...

But encounter an error: "Uncaught SyntaxError: Unexpected identifier(…)". Any idea?

Answers
nr: #1 dodano: 2016-12-24 10:12

You can get it from hidden input:

@{ 
    string fileName = "Score_List_" + DateTime.Now.ToShortDateString();
}

<input id="file-name" type="hidden" value="@fileName" />

In javascript:

...
{
    extend: 'excelHtml5',
    text: $("#file-name").val(),
    title:'List', //title & file name
}
...
nr: #2 dodano: 2016-12-26 21:12

I think It is completely unnecessary to use a hidden input here. The actual issue was in below line of code,

<script>
    // assign C# variable to JavaScript variable.
    var FileName = @Html.Raw(@fileName);
</script>

You should have used single or double quotes around @Html.Raw(@fileName) to make it a string value in JS.

<script>
    // assign C# variable to JavaScript variable.
    var FileName = '@Html.Raw(@fileName)';
</script>

Next time, if you encounter any error in dynamically generating JS script, you better check the generated code of page in browser.

Source Show
◀ Wstecz