I want to save all data of a form.
My form has these elements-
( Using Postman Plugin )
My controller is like this-
[HttpPost]
public async Task<IActionResult> Insert(IFormCollection data)
{
return Ok(data);
}
So, I am getting something like this-
[
{
"key": "user_id",
"value": [
"'12'"
]
},
{
"key": "title",
"value": [
"123"
]
},
{
"key": "text[]",
"value": [
"werwer",
"ghj"
]
}
]
I want to get the value of texts.
So, for this case-
"werwer",
"ghj"
So, I have tried something like this-
foreach (string description in data["text"])
{
// description => empty
}
and also tried this-
data.text
and also-
data->text
But nothing works for me.
Can anyone please help?
Thanks in advance for helping.
Submit your form with the developer tools open (F12) and you’ll see the form post in the network tab. Click the relevant request and check out the Form Data section. In this example you can see that firstName has been submitted as form data and so should be available to ASP.NET Core.
Create New ASP.NET MVC 5 Project and Add Controller, Models and Views. 2. Retrieve Form Data using FormCollection Object. 3. Retrieve Form Data using Model Binder 3. Retrieve Form Data Directly from the Model Class 4. Retrieve Form Data using UpdateModel class 1. Create New ASP.NET MVC 5 Project and Add Controller, Models and Views. 1.
If the form uses POST, the form data is placed in the request body. For POSTed data, the enctype attribute specifies the format of the request body: Form data is encoded as name/value pairs, similar to a URI query string. This is the default format for POST.
ASP.NET MVC Core will bind the form data to your model automatically. This also means we won’t find ourselves constantly updating the Index action every time we need to handle another value submitted via the form.
Why not loop through each keys and if the key is "text", get the values. Since the value is a comma seperated string, you can call the Split
method on that to get an array which contains 2 items( from your sample input).
foreach (string description in data.Keys)
{
if (description.Equals("text"))
{
var v = data[description];
var stringItems = v.Split(',');
foreach (var stringItem in stringItems)
{
//do something with stringItem
}
}
}
BTW, the key should be text
, not text[]
. Even if you have muliple input fields with the same name "text", when you submit, It will be a single key ("text"
) with 2 items int he value property
{
"key": "text",
"value": [
"werwer",
"ghj"
]
}
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