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.
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 ;-)?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With