Javascript int variable from ASP.NET MVC model data?

I need to get the model data into a javascript variable and use it as an int to compare values. But I can only figure out how to get the model data as strings, otherwise the compiler complains.

So how can I get max and taskBudgetHours as int variables in Javascript?

<script type="text/javascript">
    $(document).ready(function () {
        $("#taskForm").submit(function (e) {
            var taskBudgetHours = $('#BudgetHours').val();
            var max = '<%: Model.Project.RemainingBudgetHours %>';

            alert(taskBudgetHours);
            alert(max);

            if (taskBudgetHours <= max) { //This doesn't work, seems to treat it as strings...
                return true;
            }
            else {
                //Prevent the submit event and remain on the screen
                alert('There are only ' + max + ' hours left of the project hours.');
                return false;
            }
        });
    });
</script>
+3
source share
2 answers

For maxdo not put quotation marks there:

var max = <%: Model.Project.RemainingBudgetHours %>;

To taskBudgetHoursuse the built-in JavaScript function parseInt:

var taskBudgetHours = parseInt($('#BudgetHours').val(), 10);

Note the use of the radix parameter for parseInt; this prevents, for example, "020"as being parsed as octal:

parseInt("020") === 16 // true!
+4
source

Model.Project.RemainingBudgetHours , , taskBudgetHours. , :

var max = parseInt('<%: Model.Project.RemainingBudgetHours %>') 
0

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


All Articles