How do I accept an array as an ASP.NET MVC controller action parameter?

后端 未结 5 873
遥遥无期
遥遥无期 2020-11-27 13:06

I have an ASP.net MVC controller called Designs that has an action with the following signature:

public ActionResult Multiple(int[] ids)
         


        
5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-27 13:37

    To extend on Darin Dimitrov's answer, something you can get away with is accepting a simple string in your URL parameter and converting it to an array yourself:

    public ActionResult Multiple(string ids){
      int[] idsArray = ids.Split(',').Select(int.Parse).ToArray();
      /* ...process results... */
    }
    

    If you get a parse error while doing this (because someone passed you a malformed array), you can cause your exception handler to return a 400 Bad Request error instead of the default, more unfriendly 404 Not Found error that MVC returns when an endpoint is not found.

提交回复
热议问题