user1451111
user1451111

Reputation: 1943

ASP.NET Web API - how to pass unknown number of form-encoded POST values

The front-end of my application can send unknown number of POST values inside a form. Fro example in some cases there will be 3 values coming from certain textboxes, in some cases there will be 6 values coming from textboxes, dropdowns etc. The backend is ASP.NET Web API. I know that a simple .NET value can be passed in URI parameter to a "POST Action" using FromURI attribute and a complex type can be passed in body and fetched using FromBody attribute, in any POST Action. But in my case the number of form data values will NOT be constant rather variable and I can't use a pre-defined class to hold values using 'FromBody' attribute.

How can I tackle this situation?

Upvotes: 1

Views: 309

Answers (2)

Jon Susiak
Jon Susiak

Reputation: 4978

You can use the FormDataCollection from the System.Net.Http.Formatting namespace.

public class ApiFormsController : ApiController
{
    [HttpPost]
    public IHttpActionResult PostForm(FormDataCollection form)
    {
        NameValueCollection items = form.ReadAsNameValueCollection();
        foreach (string key in items.AllKeys)
        {
            string name = key;
            string val = items[key];
        }
        return Ok();
    }
}

Upvotes: 2

garret
garret

Reputation: 1134

Try to send this properties as list of properties. Make model something like this:

public class PostModel
{
    public IEnumerable<PropertyModel> Properties { get; set; }
}
public class PropertyModel
{
    public string Value { get; set; }
    public string Source { get; set; }
    // etc.
}

And action:

public IHttpActionResult Post(PostModel model)
{
    //Omited
     return Ok();
}

Upvotes: 0

Related Questions