Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.net core why can i get the IFormCollection by key the alone

lets say i have an

<form method="post" action"/user/create">
    <input type="text" name="FirstName" placeholder="FirstName" />
    <button type="submit">Submit</button>
</form>

I want to access my input value FirstName in my action method.

public IActionResult Create(IFormCollection form)
{
    string FirstName = form.Keys["FirstName"];
    return View();
}

It giving an error "Cannot apply indexing with [] to an expresion of type ICollection "

I know i can iterate and put a if statement but I found that takes so much code. I just started learning c# but in Node.js and Python its so easy to get form post values, for example in node.

request.body.FirstName;

Thats it. I'm looking for something similar without that iteration or creating a poco class.

thanks.

like image 764
Millenial2020 Avatar asked Aug 17 '17 03:08

Millenial2020


1 Answers

Simple Answer

You can use form["FirstName"] or form.Get("FirstName").


edit: You mentioned, you do not want to create a poco. But still, consider that if you have multiple parameters:

Original Content:

I'd prefer creating a class (like person, which has a FirstName Property) and use the advantage of builtin serialization.

If your Form-Parameters look like this:

{
  "FirstName": "John",
  "LastName": "Doe"
}

Then your class should be:

public class Person {
  public string FirstName {get;set;}
  public string LastName {get;set;}
}

And your Create Method should be like this

public IActionResult Create([FromForm]Person p)
{
    string FirstName = p.FirstName;
}

It will automatically parse the form parameters in to your Person object.

What a clean way reading form params, isn't it ;-)?

like image 82
Benjamin Schäublin Avatar answered Sep 28 '22 02:09

Benjamin Schäublin