Pass C # variable to helper function in jsrender template

I need to pass one of the values ​​of my model to the jsrender function. I tried using @ to access a C # variable, but not working. Below is my code

<script type="text/x-jsrender" id="TemplateDate">>
 {{:~formatTemplateDate(Model.EstimatedCompletionDate)}} 
</script>

This is my helper function.

$.views.helpers({
    formatTemplateDate: function (dateEstimated) {
        "use strict";
        if (dateEstimated !== null) {
            if (!isSafari) {
                var options = {
                    year: "numeric",
                    month: "short",
                    day: "numeric",
                    hour: "2-digit",
                    minute: "2-digit"
                };
                return dateEstimated.toLocaleTimeString("en-us", options);
            } else {
                return dateEstimated;
            }
        } else {
            return null;
        }
    }
});

This is the error I get on the page

Error: n.toLocaleDateString is not a function.

Thanks in advance.

Dinesh.

+4
source share
2 answers

I found a fix. We cannot pass the value of the datetime @ Model.EstimatedCompletion variable to a helper function. You need to convert it to a string and to a helper function you need to convert it back to Datetime (). The following is a modified code.

<script type="text/x-jsrender" id="TemplateDate">>
 {{:~formatTemplateDate('@Model.EstimatedCompletionDate')}} 
</script>

, var formatedDate = new Date (date);

$.views.helpers({
    format: function (date) {
        "use strict";
        var formatedDate = new Date(date);
        if (!isSafari) {
            var options = {
                year: "numeric",
                month: "short",
                day: "numeric"
            };
            return formatedDate.toLocaleDateString("en-us", options);
        } else {
            return formatedDate;
        }
    }
});

,

.

+1

@Html.Raw():

<script type="text/x-jsrender" id="TemplateDate">>
     {{:~formatTemplateDate('@Html.Raw(Model.EstimatedCompletionDate))')}} 
</script>
0

Source: https://habr.com/ru/post/1677632/


All Articles