MVC Web API post an array of integers via x-www-fo

2019-07-15 09:09发布

I am trying to do something which I thought would be fairly simple. I have an HTML form that posts a set of integer inputs, all called "Level":

<form action="/api/levels" method="post">
<input name="Level" value="10" />
<input name="Level" value="20" />
<input name="Level" value="30" />
<button type="submit">submit</button>
</form>

I am trying to receive this into an MVC Web API controller method like this:

public void Post(int[] Level)
{

}

Diagnosing with Chrome's network tools confirms the request contains form data as I would expect:

Level=10&Level=20&Level=30

The problem is that the Level parameter is always null. I would obviously want it to be an array with 3 elements of values 10, 20 and 30.

There are so many posts about similar things, but I can't find anything that talks about Web API model binding rather than MVC, or those that do seem to be complaining about changes made in older versions release candidates.

Can somebody point me in the right direction please?

1条回答
beautiful°
2楼-- · 2019-07-15 10:00

If you want the body Level=10&Level=20&Level=30 to be bound, you will need your action method parameter to be like so.

public HttpResponseMessage Post(MyClass c)
{
    // Use c.Level array here
}

public class MyClass
{
    public int[] Level { get; set; }
}

Instead, if you want the action method parameter to be int[] Level, your HTTP message must be like so.

POST http://server/api/levels HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Content-Length: 11

=10&=20&=30

For this, have the form like so.

<form action="/api/levels" method="post">
    <input name="" value="10" />
    <input name="" value="20" />
    <input name="" value="30" />
    <button type="submit">submit</button>
</form>

The reason for this weirdness is that ASP.NET Web API binds the entire body into one parameter.

查看更多
登录 后发表回答