Handling Arrays of HTML Input Elements with Request.Form Like PHP

前端 未结 3 1966
温柔的废话
温柔的废话 2021-01-12 03:28

How can I properly receive these Array of Inputs on asp.net?




        
相关标签:
3条回答
  • 2021-01-12 04:10

    You can use a standard string split - this is all php does for you behind the scenes. PHP is not a strongly typed language however which means that it is a LOT easier for them to provide the "appearance" of this functionality.

    The reality is that php is just allowing you to provide comma delimited input and it automatically splits it for you.

    So... if you want to do this in asp.net, you can use the same input name a number of times and it will be returned with the request object as a comma delimited list. I would not recommend using this approach for user entered input, but it will work fine if you are contrrolling the input like combining a list into a hidden input from a jquery script.

    To get your head around what is happening (with php too.. all web dev techs are using the same http rules), just try posting a form with an input (don't set runat server) that is there twice.

    <input type="text" name="MyTest" value="MyVal1" />
    <input type="text" name="MyTest" value="MyVal2" />
    

    On pageload add this

    if(IsPostBack)
    {
       Response.Write(Request["MyTest"]);
    }
    

    You should see

    MyVal1,MyVal2

    On the screen.

    Now, if you want this into an array, you can:

    string[] myvals = Request["MyTest"].Split(',');
    

    if you want Integers or other datatypes (php doesn't know/care what a datatype is really), you will have to loop through it and parse it into another array/generic list.

    I don't know what your wanting as an end result, but understanding what the browser posts back is the first step and the short answer is...

    Yes, ASP.NET can do this to (just a little more manually).

    0 讨论(0)
  • 2021-01-12 04:13

    These are not arrays of inputs. HTML doesn't have a concept of arrays.

    These are simply groups of inputs with the same name.

    What are you trying to achieve? Why are you not using server side controls?


    Update:

    You can access the Request.Forms collection - it will hold the posted form elements.

    Alternatively, use server side controls - you will be able to access these by ID.

    0 讨论(0)
  • 2021-01-12 04:22

    actually, it does exist with asp.net. - you can use

    string[] MyTest = Request.Form.GetValues("MyTest");
    

    or

    string[] MyTest = Request.QueryString.GetValues("MyTest");
    
    0 讨论(0)
提交回复
热议问题