Search code examples
c#asp.netasp.net-core.net-6.0dynamicform

ASP.NET Core Web App - Dynamic form values passed to OnPost


I'm creating an ASP.NET Core Web App with .NET 6 and I'm trying to find a way to pass a dynamic list of variables back to the OnPost handler. Here's the details, I create a form on the page during the OnGet. I don’t know how many fields, or the types, this form will have at design time. It can be as few as one or as many as 20. They could be text fields, dates, integers, checkboxes, etc., but I don't know ahead of time. When the user submits this form, I need to collect all the values in the OnPost and display the results; the results are also dynamic but that's a separate issue. So how do I get the values? I can't create BindProperties or create a Model, ‘cause I don't know how many or what they are. I can easily assign a unique Id/Name to the form while I'm building it, Param1, Param2, Param3, etc. but that's not the important part. I can't imagine that I'm the first person to attempt this, but I can't find any examples of how to accomplish this, at least in Asp.Net Core .NET6


Solution

  • Since you aren't using model binding you can access the form data directly and loop through all the data

    var formData = Request.Form;
    
    foreach(var data in formData)
    {
        // Name attribute from the form
        string keyName = data.Key;
        // Value the user entered
        string keyValue = data.Value;
    }