Collin O'Connor
Collin O'Connor

Reputation: 1351

Javascript error with Viewdata

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

Upvotes: 2

Views: 1163

Answers (1)

Nicholas Murray
Nicholas Murray

Reputation: 13533

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.

Upvotes: 4

Related Questions