Frage

I need to pass a list(containing at least 3 items) to MVC HttpGet Action... but i don't know how to pass that... Is there any other way instead of using Request Query String? using Request Query String is off the chart for me, since the list is created dynamically in client side..

    public ActionResult Customer(List customer)
    {

        return View();
    }

please guide me through this... Thanks in advance..

War es hilfreich?

Lösung

You could do this by manually parsing the FormCollection object, but it would make for tedious code. However this may be necessary if you can't control the names of the POSTed values.

public ActionResult Customer(FormCollection response)
{
    for (int i = 0; i < response["CustomerCount"]; i++
    {
        list.Add(
            new Customer
            {
                ID = response["Customer" + i + ".ID"],
                Name = response["Customer" + i + ".Name"],
                ...
            });
    }
}

But a much cleaner way is using MVC's automatic binding, which works for lists as well:

The query string from user:

/Customer/Add?myList[0].ID=2&myList[0].Name=Bob&myList[1].ID=18&myList[1].Name=Alice

The controller:

public CustomerController : Controller
{
    public ActionResult Add(List<Customer> myList)
    {
        var test = myList.Count; // 2
        var test2 = myList[1].Name; // Alice
    }
}

If possible, using the HtmlHelper methods in your Razor view to create those inputs, takes all the guesswork out of this. An example to edit current customers:

@model MyNamespace.ViewModels.CustomerEditViewModel
@Html.BeginForm("Edit", "Customer")
{
    @* Show all current customers for editing *@
    @for (int i=0; i < Model.Customers.Count; i++)
    {
        @Html.TextBoxFor(x => x.Customers[i].ID)
        @Html.TextBoxFor(x => x.Customers[i].Name)
    }

    <input type="submit" />
}

Note: Customers is a List<Customer> in the CustomerEditViewModel class passed with return View(myViewModel);

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top