3

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>
1
  • I edited your code a bit; the most noteworthy thing is that if you do return false, you don't need to do e.preventDefault() Commented Jan 11, 2011 at 23:11

2 Answers 2

4

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!
Sign up to request clarification or add additional context in comments.

2 Comments

Ok, but for max is it valid syntax? I get a complaint from ReSharper saying it's expecting an expression if I remove the quotes...
You're mixing ASP.NET with C# with JavaScript and you expect ReSharper to be smart enough to figure that out? No way! The more important test is, does it work when you run it in the browser?
1

I would try to assign the Model.Project.RemainingBudgetHours to a hidden field on page load and then get its value as you do with the taskBudgetHours. Also not quite sure but you can try:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.