ASP.NET MVC Model数据中的Javascript int变量?(Javascript int variable from ASP.NET MVC Model data?)

我需要将模型数据转换为javascript变量并将其用作int来比较值。 但我只能弄清楚如何将模型数据作为字符串,否则编译器会抱怨。

那么如何在Javascript中将max和taskBudgetHours作为int变量?

<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>

I need to get 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 the max and taskBudgetHours as int variables in the 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>

最满意答案

max ,不要在它周围加上引号:

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

对于taskBudgetHours ,使用内置的JavaScript parseInt函数:

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

注意parseInt使用radix参数; 这可以防止例如"020"被解析为八进制:

parseInt("020") === 16 // true!

For max, don't put quotes around it:

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

For taskBudgetHours, use the built-in JavaScript parseInt function:

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

Note the use of the radix parameter for parseInt; this prevents e.g. "020" as being parsed as octal:

parseInt("020") === 16 // true!

更多推荐