[c#] How can I get all element values from Request.Form without specifying exactly which one with .GetValues("ElementIdName")

Currently using the below code to create a string array (elements) that contains all string values from Request.Form.GetValues("ElementIdName"), the problem is that in order for this to work all my dropdown lists in my View have to have the same element ID name which I don't want them to for obvious reasons. So I am wondering if there's any way for me to get all the string values from Request.Form without explicitly specifying the element name. Ideally I would want to get all dropdown list values only, I am not too hot in C# but isn't there some way to get all element ID's starting with say "List" + "**", so I could name my lists List1, List2, List3 etc.

Thanks..

[HttpPost]
public ActionResult OrderProcessor()
{
    string[] elements;
    elements = Request.Form.GetValues("List");

    int[] pidarray = new int[elements.Length];

    //Convert all string values in elements into int and assign to pidarray
    for (int x = 0; x < elements.Length; x++)
    {

        pidarray[x] = Convert.ToInt32(elements[x].ToString()); 
    }

    //This is the other alternative, painful way which I don't want use.

    //int id1 = int.Parse(Request.Form["List1"]);
    //int id2 = int.Parse(Request.Form["List2"]);

    //List<int> pidlist = new List<int>();
    //pidlist.Add(id1);
    //pidlist.Add(id2);

    var order = new Order();

    foreach (var productId in pidarray)
    {
        var orderdetails = new OrderDetail();

        orderdetails.ProductID = productId;
        order.OrderDetails.Add(orderdetails);
        order.OrderDate = DateTime.Now;
    }

    context.Orders.AddObject(order);
    context.SaveChanges();
    return View(order);
}
         

This question is related to c# asp.net asp.net-mvc asp.net-mvc-2 httpwebrequest

The answer is


Request.Form is a NameValueCollection. In NameValueCollection you can find the GetAllValues() method.

By the way the LINQ method also works.


Waqas Raja's answer with some LINQ lambda fun:

List<int> listValues = new List<int>();
Request.Form.AllKeys
    .Where(n => n.StartsWith("List"))
    .ToList()
    .ForEach(x => listValues.Add(int.Parse(Request.Form[x])));

Here is a way to do it without adding an ID to the form elements.

<form method="post">
    ...
    <select name="List">
        <option value="1">Test1</option>
        <option value="2">Test2</option>
    </select>
    <select name="List">
        <option value="3">Test3</option>
        <option value="4">Test4</option>
    </select>
    ...
</form>

public ActionResult OrderProcessor()
{
    string[] ids = Request.Form.GetValues("List");
}

Then ids will contain all the selected option values from the select lists. Also, you could go down the Model Binder route like so:

public class OrderModel
{
    public string[] List { get; set; }
}

public ActionResult OrderProcessor(OrderModel model)
{
    string[] ids = model.List;
}

Hope this helps.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to asp.net-mvc

Using Lato fonts in my css (@font-face) Better solution without exluding fields from Binding Vue.js get selected option on @change You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to send json data in POST request using C# VS 2017 Metadata file '.dll could not be found The default XML namespace of the project must be the MSBuild XML namespace How to create roles in ASP.NET Core and assign them to users? The model item passed into the dictionary is of type .. but this dictionary requires a model item of type How to use npm with ASP.NET Core

Examples related to asp.net-mvc-2

Better solution without exluding fields from Binding How to set the value of a hidden field from a controller in mvc Making a Simple Ajax call to controller in asp.net mvc ASP.Net MVC - Read File from HttpPostedFileBase without save Session state can only be used when enableSessionState is set to true either in a configuration Using Tempdata in ASP.NET MVC - Best practice Getting index value on razor foreach Current date and time - Default in MVC razor Url.Action parameters? How can I get all element values from Request.Form without specifying exactly which one with .GetValues("ElementIdName")

Examples related to httpwebrequest

C# HttpWebRequest The underlying connection was closed: An unexpected error occurred on a send How to properly make a http web GET request Send JSON via POST in C# and Receive the JSON returned? How to create JSON post to api using C# Use C# HttpWebRequest to send json to web service Post form data using HttpWebRequest HttpWebRequest-The remote server returned an error: (400) Bad Request Get host domain from URL? How to ignore the certificate check when ssl Receiving JSON data back from HTTP request