s.k.paul
s.k.paul

Reputation: 7291

Check whether an element exists in mvc formcollection

I am receiving some data in mvc controller as FormCollection. I would like to check if there is a particular key exists in the formcollection.

 public JsonResult FullRetailerUpdate(FormCollection data)
 {
     //I want to check if 
     //data["AnElement"] is exist
 }

Please help.

Upvotes: 9

Views: 11147

Answers (2)

Darren Wood
Darren Wood

Reputation: 1528

I know that the question was about FormCollection but for those using IFormCollection here is the solution.

public IActionResult GetProjectDelivery(IFormCollection data)
{
    if (data.ContainsKey("AnElement"))
    {
        // do stuff
    }
    else
    {
        // do stuff
    }
}

Upvotes: 1

Kartikeya Khosla
Kartikeya Khosla

Reputation: 18873

Try using .Contains():-

 public JsonResult FullRetailerUpdate(FormCollection data)
 {
    if (data.AllKeys.Contains("AnElement")) 
    {
      // Your Stuff
    }
    else
    {
      // Your Stuff
    }   
 }

Upvotes: 20

Related Questions