Monday, February 21, 2011

Can PHP array passed POST method to catch in ASP.NET MVC?

Can PHP array passed POST method to catch in ASP.NET MVC?

Query string: WebAccess/ArrayTest?val[]=1&val[]=2&val[]=3

I write: ActionResult ArrayTest (String[] val)

But this only works if the query string to remove the "[]"

From stackoverflow
  • (not an answer - but its difficult to explain this using a S.O. comment)

    You've rather confused things by suggesting that this is really anything to do with PHP. Also, you don't say which '[]' you removed to make it work. The unenlightened asp programmers out there might find it easier to understand:

    <form method='POST' action='something.asp'>
       <input type='text' name='val[]'>
       <input type='text' name='val[]'>
       <input type='text' name='val[]'>
       <input type='submit' value='go'>
    </form>
    

    Using some web development languages the data from each the three text fields is subsequently available in an array named 'val'. How to replicate this behaviour in asp.net?

    C.

  • The built in DefaultModelBinder in ASP.NET MVC can't handle rails/php/jquery1.4 style array posts (which is what you're referring to with val[]=1&val[]=2&val[]=3).

    You have to either create a custom modelbinder (google it, lots of examples) or adding indices inside the bracket like so:

    val[0]=1&val[1]=2&val[2]=3
    

    And the indices must not have any missing numbers.

    I have fixed this with a script that on submit of the form just adds the indices. i.e. in jQuery:

    $('form').find('input, select, textarea').attr('name', function(index, old) {
        return old.replace(/\[\]/, '[' + index + ']');
    });
    

0 comments:

Post a Comment