我正在使用带有for循环的表单,具体取决于将要创建的表单输入字段的数量。我想返回一个Formcollection列表。我知道formcollection只返回一种形式,但是我想返回许多形式(列表) 所以我的控制器方法只适用于1种形式 我的控制器:
[HttpPost]
public ActionResult SecondStepProcessValid(FormCollection form)
{
List<Customer> itemList = new List<Customer>();
int i = 0;
itemList.Add(new Customer()
{
Name = form["Name"],
Emailaddress = form["Email"],
HouseNumber = Int32.Parse(form["HouseNumber"]),
Zipcode = form["Zipcode"]
});
foreach (var c in itemList)
{
customerRepository.Create(c);
}
return View("ThirdStepProcess");
}
我的观点
<form method="post" action="@Url.Action("SecondStepProcessValid")">
@for (int i = 0; i < Model.Amount; i++)
{
<div class="space">
<div><br /></div>
<div>Guest@(@i + 1)</div>
</div>
<div class="space">
<div>Name</div>
<div>@Html.TextBox("Name", Model.NewCustomers[i].Name)</div>
</div>
<div class="space">
<div>Email</div>
<div>@Html.TextBox("Email", Model.NewCustomers[i].Emailaddress)</div>
</div>
<div class="space">
<div>House Number</div>
<div>@Html.TextBox("HouseNumber", Model.NewCustomers[i].HouseNumber)</div>
</div>
<div class="space">
<div>Zipcode</div>
<div>@Html.TextBox("Zipcode", Model.NewCustomers[i].Zipcode)</div>
</div>
<input type="hidden" name="Index" value="@i" />
}
<input type="submit" value="Step 3" />
</form>
答案 0 :(得分:1)
您不能同时发布多个表单。但是您也可以以一个表单或多个List<T>
发布多个项目。
为此,您需要使视图强类型化,然后在操作中可以使用类型为List<Customer>
的参数或具有类型为List<Customer>
的属性的容器视图模型,如下所示:
public class CustomersModel
{
public int Amount { get; set; }
public List<Customer> NewCustomers{ get; set; }
CustomersModel()
{
Amount = new List<Customer>();
}
}
将视图更改为该模型的强类型,并使用强类型的助手来呈现输入控件,以避免使用魔术字符串可能发生的愚蠢的错字错误,并从模型和Visual Studio的智能中受益,并从错误中编译时间安全:
@model YourNamespace.Models.CustomersModel
@for (int i = 0; i < Model.Amount; i++)
{
<div class="space">
<div><br /></div>
<div>Gast @(@i + 1)</div>
</div>
<div class="space">
<div>Name</div>
<div>@Html.TextBoxFor(x => Model.NewCustomers[i].Name)</div>
</div>
<div class="space">
<div>Email</div>
<div>@Html.TextBoxFor(x => Model.NewCustomers[i].Emailaddress)</div>
</div>
<div class="space">
<div>House Number</div>
<div>@Html.TextBoxFor(x => Model.NewCustomers[i].HouseNumber)</div>
</div>
<div class="space">
<div>Zipcode</div>
<div>@Html.TextBox(For(x => Model.NewCustomers[i].Zipcode)</div>
</div>
@Html.HiddenFor(x=> Model.NewCustomers[i].Id,i)
}
现在在控制器中,您可以拥有一个要对其进行强键入的参数:
[HttpPost]
public ActionResult SecondStepProcessValid(CustomersModel model)
{
foreach (var c in model.NewCustomers)
{
customerRepository.Create(c);
}
return View("ThirdStepProcess");
}
希望它能提供想法。