HendPro12
HendPro12

Reputation: 1104

FormCollection Check if Null

In this conditional statement I have tried the last portion in order to try and execute a section of code if my Form Collection is empty.

if ((myDT == null) || (myCollection.GetKey(0).ToString() == "heatSearch") || (myCollection == null))
{
    //some code here
}

Each time I run the code and the Form Collection is empty, at which time this condition should be true, my application crashes and I receive this error: Index was out of range. Must be non-negative and less than the size of the collection.

Some more information...this check is being performed in an ActionResult called by an AJAX post. The post is what fails and returns the error at this line shown here: <b> Source File: </b> c:\Users\D\Documents\Visual Studio 2012\Projects\TheMProject(1)\TheMProject\Models\HomeModel.cs<b> &nbsp;&nbsp; Line: </b> 936

Line 936 is the one with the if.

Upvotes: 0

Views: 4905

Answers (3)

JBatz
JBatz

Reputation: 176

if ((myDT == null) || (myCollection == null) || (myCollection.Count > 0) )
{
    //some code here
}

is what I'd do

Upvotes: 0

Conrado Costa
Conrado Costa

Reputation: 435

Fix it:

if ((myDT == null) || (myCollection == null) || (myCollection.GetKey(0).ToString() == "heatSearch"))
{
    //some code here
}

You're calling myCollection.GetKey(0) before test if myCollection is null.

Upvotes: 3

Have you tried...

public ActionResult MyAction(FormCollection f)
{
    if (f.Count == 0)
        {
            Debug.WriteLine("Hello");
        }

        return View();
}

Upvotes: 0

Related Questions