Manog
Manog

Reputation: 71

Binding strings to list in controller

I have a form in View where are multiple fields. I send them to controller and I want to bind them to List. How can I achieve this?

For now i have this code

View

using (Html.BeginForm("GetVendorInvoice", "Sale", FormMethod.Get))
{
    foreach (var invoice in Model.VendorInvoices)
    { 
        @Html.Hidden("invoiceId", invoice.InvoiceId)
    }
    <input type="submit" value="Wszystkie na raz"/>
}

Controller:

public ActionResult GetVendorInvoice(List<string> invoiceIdList) {
...}

I read some article that said it shoud work but actually it does not. Any sugestions?

Upvotes: 1

Views: 142

Answers (3)

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62498

You have property name InvoiceId while in action you paremeter is invoiceIdList which is wrong and list will be null in the action, do like this in action:

public ActionResult GetVendorInvoice(List<string> InvoiceId) {
    ...}

or you can do like this:

foreach (var invoice in Model.VendorInvoices)
    { 
        @Html.Hidden("InvoiceId", invoice.InvoiceId)
    }

action:

public ActionResult GetVendorInvoice(List<string> invoiceId) {
...}

Upvotes: 2

Manog
Manog

Reputation: 71

I heve found the answer. First of all there was an error. Filed name in view was different from parameter name in controller. When i fixed this i have got a string of hidden fields values separated with commas. Now i have to split this string and everithing is fine now. Thanks for Your effort.

Upvotes: 0

Ian Newson
Ian Newson

Reputation: 7949

Actions:

public virtual ActionResult Index()
{
    return View(new HomepageModel()
    {
            Strings = new[] {"one", "two", "three"}
    });
}

[HttpPost]
public ActionResult Index(List<string> strings)
{
    throw new Exception(String.Join(", ", strings));
}

View:

@using (Html.BeginForm())
{

    for (int i = 0; i < Model.Strings.Length; ++i)
     {
         @Html.HiddenFor(model => model.Strings[i])
     }

    <input type="submit" value="submit" />
}

You should use the HiddenFor helper method instead of Hidden, as this is strongly typed and will ensure your view matches the model. Using the indexer will generate the correct names for the hidden fields.

Upvotes: 0

Related Questions