将列表传递给MVC中的HttpGet方法的替代方法

时间:2014-05-07 11:17:08

标签: asp.net-mvc list parameter-passing

我需要将一个列表(包含至少3个项目)传递给MVC HttpGet Action ...但我不知道如何传递...有没有其他方法而不是使用请求查询字符串?使用请求查询字符串对我来说不在图表中,因为列表是在客户端动态创建的。

    public ActionResult Customer(List customer)
    {

        return View();
    }

请引导我完成这个...提前致谢..

1 个答案:

答案 0 :(得分:1)

您可以通过手动解析FormCollection对象来完成此操作,但这会产生繁琐的代码。但是,如果您无法控制POSTed值的名称,则可能需要这样做。

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"],
                ...
            });
    }
}

但更简洁的方法是使用MVC的自动绑定,这也适用于列表:

来自用户的查询字符串:

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

控制器:

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

如果可能,使用Razor视图中的HtmlHelper方法创建这些输入,可以完成所有猜测。编辑当前客户的示例:

@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" />
}

注意:客户是List<Customer>类的CustomerEditViewModelreturn View(myViewModel);