Get posted value In C# ASP.NET
Solution 1
Request.Form is a NameValueCollection
, an object that can store a collection of items under the same key and the ToString
displays the values in CSV format.
Markup:
<input type="text" name="postField[]" />
<input type="text" name="postField[]" />
<input type="text" name="postField[]" />
<input type="text" name="postField[]" />
<asp:Button Text="text" runat="server" OnClick="ClickEv" />
Code behind:
protected void ClickEv(object sender, EventArgs e)
{
var postedValues = Request.Form.GetValues("postField[]");
foreach (var value in postedValues)
{
}
}
Solution 2
You would use Request.Form[]
. Or if your form and fields had runat="server"
and ids, you could just use the id in the codebehind and the .Text()
method to access its value.
Solution 3
You can access everything that gets sent back to the server by using the Request object.
Request.Form.Items
Is a collection that will contain the item you are looking for.
amd
Updated on April 01, 2020Comments
-
amd about 4 years
I have a dynamic form that allow to add many fields dynamically,
I Know how to get the value of single field in aspnet using : Request.Form["myField"],but here i have more than field and i dont know the count of these fields since these are dynamic
the fields name is "orders[]"
ex:
<form> <input type="text" name="orders[]" value="order1" /> <input type="text" name="orders[]" value="order2" /> <input type="text" name="orders[]" value="order3" /> </form>
In php, i get the values as an array by accessing
$_POST['orders']
;ex:
$orders = $_POST['orders']; foreach($orders as $order){ //execute ... }
how can I do this in c# ?
-
amd about 12 yearsNO I Cant use the runat server since the fields may be added in the client side
-
Code Maverick about 12 yearsThat's fine, you should still be able to use the aforementioned
Request.Form[]
to pull all posted form fields and their values. -
amd about 12 yearsyes i can use it, but the problem is all the field are the same name
orders[]
so Request.Form["orders"] will get NULL -
Code Maverick about 12 yearsYou really should expand on why you are using ASP.NET WebForms and C#, yet not taking advantage of it's default functionality such as forms that are
runat="server"
that use ASP.NET WebControls with IDs and runat="server" so you can simply access them in the code-behind via their IDs. To answer your comment, you need to put anID
attribute on each input to access it viaRequest.Form[]
. -
amd about 12 yearsI mentioned above that the fields are dynamic,so the fields are generated at the client side,every time the number of fields will be different,in this scenario there is no way to use the server side controls