Check whether an element exists in mvc formcollection
Asked Answered
S

2

9

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.

Scintillator answered 4/12, 2014 at 7:29 Comment(0)
C
20

Try using .Contains():-

 public JsonResult FullRetailerUpdate(FormCollection data)
 {
    if (data.AllKeys.Contains("AnElement")) 
    {
      // Your Stuff
    }
    else
    {
      // Your Stuff
    }   
 }
Cockahoop answered 4/12, 2014 at 7:31 Comment(1)
contains no more exist in Allkeys now.Atoll
M
1

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
    }
}
Maytime answered 15/12, 2019 at 23:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.