开发者

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

Can PHP array passed POST method t开发者_StackOverflow社区o 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 "[]"


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 + ']');
});


(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.


  public class PhpStyleArrayBinder : DefaultModelBinder,IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var val = bindingContext.ValueProvider.GetValue(bindingContext.ModelName+"[]");
            if (val != null)
                return val;
            return base.BindModel(controllerContext, bindingContext);
        }
    }

usage:

public JsonResult Get([ModelBinder(typeof (PhpStyleArrayBinder))] IEnumerable<string> data)
        {
            //
        }

http://pavelsvetlov.blogspot.com/2016/04/mvcnet-modelbinder-phpstyle-array.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜