我想我有一个非常简单的场景,但似乎无法掌握如何在.NET的MVC框架中做到这一点.最简单的是,这是一种具有排名的人.我想在一个页面上列出他们名字旁边的每个人的姓名和文本框.这是(Razor)Html的样子:
@using (Html.BeginForm()) {
<fieldset>
@foreach (var b in Model.Ballots) {
<p>
<label>@b.Person.FullName</label>
@Html.TextBox("Rank")
@Html.ValidationMessage("Rank")
</p>
}
</fieldset>
<input type="submit" value="Vote" />
Run Code Online (Sandbox Code Playgroud)
}
选票是一个简单的对象,有一个人和一个排名:
public class Ballot {
public Person Person { get; set; }
[Range(1, 6, ErrorMessage="The voting range is 1 through 6")]
public int Rank { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
这是我的控制器处理表单提交的方法,但它永远不会被调用.
[AcceptVerbs("POST")]
public ActionResult Vote(IEnumerable<Ballot> ballots) {
return View("BallotComplete");
}
Run Code Online (Sandbox Code Playgroud)
如何迭代表单提交回服务器的所有模型?
我使用Customer对象做了一个快速示例,但我认为它类似.请注意表单字段的标签方式.以控制器中的参数名称作为前缀.需要索引作为集合处理.你的可能会稍微复杂一点,因为你有一个嵌套的类.(选票内的人).我认为通过做客户[@counter] .Person.Id表单字段可以工作.对不起,我没有选票的例子.:)
这将是视图的相关部分:
@using (Html.BeginForm())
{
var counter = 0;
foreach (var customer in this.Model)
{
<input type="text" name="customers[@counter].Id" value="@customer.Id"/>
<input type="text" name="customers[@counter].CompanyName" value="@customer.CompanyName"/>
counter++;
}
<input type="submit" />
}
Run Code Online (Sandbox Code Playgroud)
这将是控制器的相关部分:
public ActionResult Test()
{
return View(Service.GetCustomers());
}
[HttpPost]
public ActionResult Test(Customer[] customers )
{
return View(customers);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1753 次 |
| 最近记录: |