Meco Barundis
Meco Barundis

Reputation: 51

How to post form data from razor view to WebApi as dictionary?

I have a lot of forms created with helper

Html.BeginRouteForm

I want to post it to my web api controller and I can do it with predefined DTO.

But I want to post it as dictionary, because the forms is for getting parameters from user. In each case the set of parameters can be different.

How I can do it? How I can do it better?

Thanks!

UPDATE

Here is my form:

     @using (Html.BeginRouteForm("DefaultApi", new { controller = "Products", action = "Add", httproute = "true" }))
        {
            <div class="form-group">
                Product:
                @Html.TextBoxFor(m => m.Product, new { @class = "form-control" })
            </div>
            <div class="form-group">
                Cost:
                @Html.TextBoxFor(m => m.Cost, new { @class = "form-control" })
            </div>
        }

Upvotes: 0

Views: 817

Answers (1)

Jamie Ide
Jamie Ide

Reputation: 49261

You can declare the parameter in the post action as a FormDataCollection which is derived from NameValueCollection and is very similar to a dictionary. This is the weakly typed method to post form data in MVC.

[HttpPost]
public ActionResult Edit(FormDataCollection formDataCollection)
{
    var nvc = formDataCollection.ReadAsNameValueCollection(); 
    foreach(var key in nvc)
    {
        var value = nvc[key];
    }
}

Upvotes: 1

Related Questions