Check whether an element exists in mvc formcollection

s.k.paul picture s.k.paul · Dec 4, 2014 · Viewed 9k times · Source

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.

Answer

Kartikeya Khosla picture Kartikeya Khosla · Dec 4, 2014

Try using .Contains():-

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