2

I have a link that goes to a controller that renders a page that includes this javascript.

$(document).ready(function () {
        var creditCards = '<%:(ViewData["CreditCards"])%>';
        alert(creditCards);
        if (creditCards != null) {
            var CreditCardViewData = '<%:((SelectList)ViewData["CreditCards"]).Count() %>';
            ....

The situation I am testing is when the viewData creditCards is null. I debug it and it gets to the var creditCards = '<%:(ViewData["CreditCards"])%>';line and when i click step into it jumps all the way to var CreditCardViewData = '<%:((SelectList)ViewData["CreditCards"]).Count() %>';. (Note: this page works fine when the ViewData CreditCards is not null)

After it jumps, it instantly gives the error: "argumentnullexception: Value cannot be null. Parameter name: source."

How do i prevent this error from showing up. Thanks

Collin O'Connor
  • 1,351
  • 4
  • 19
  • 31

1 Answers1

4

Try changing your code to the following to ensure that the Count() is only called if ViewData["CreditCards"] is not null.

var CreditCardViewData = '<%:((ViewData["CreditCards"]) != null) ? ((SelectList)ViewData["CreditCards"]).Count() : 0 %>'

The Count() method checks arguments for null and then throws the ArgumentNullException if it detects an invalid (null) argument.

Nicholas Murray
  • 13,305
  • 14
  • 65
  • 84
  • 1
    The JavaScript compiler checks the first argument of the if statment if that is true, if it's true it will try the second one, but if the first one is false it will ignore the second one. That way you can be sure that .count() will only be called if there is any value. – Bjarki Heiðar Mar 14 '11 at 09:31