我需要能够回发未知数量的该模型类:
public class UserRegisterModel
{
public string UserName { get; set; }
public string Password { get; set; }
public string ConfirmPassword { get; set; }
public string RepName { get; set; }
public string ContactNumber { get; set; }
}
在 List<UserRegisterModel>
到 Controller 。
我需要我的 View 有一个表单,可以将模型的多个实例发送回 Controller ,因此,例如,如果我的用户想要添加 3 个代表,他可以创建 3 个代表,并向他们提供每个详细信息以及用户名和密码,然后将它们全部发送回列表中。
我的 View 代码有这样的起点:
@model List<PicsWebApp.Models.UserRegisterModel>
@{
ViewBag.Title = "NewRep";
}
<h2>NewRep</h2>
@using (Html.BeginForm("NewRep", "Admin", FormMethod.Post, new { id = "fieldform", @class = "form" }))
{
}
有人可以告诉我完成此任务的正确方法吗?我知道我需要 javascript,以便在用户单击“添加新代表”时动态添加更多表单元素,因此这主要与 C# 有关。
最佳答案
您需要确保属性的 ID 符合标准集(当我这样做时,我使用了 Felipe 评论中的链接)。我以前这样做过,当用户单击按钮时会添加表格行。我发现最好的方法是在页面渲染之前添加一个条目,然后获取 HTML,并在 jquery 中使用它。
这是我使用过的一个函数:
$("#nameAdd").click(function (e) {
var index = $("#nameTable tr").length - 1;
e.preventDefault();
var newItem = $("<tr> \
<td> \
<span id='Names_" + index + "__FullName' /> \
</td> \
<td> \
<input class='table-editor-small update-name' id='Names_" + index + "__FirstName' name='Names[" + index + "].FirstName' type='text' value='' /> \
</td> \
<td> \
<input class='table-editor-small update-name' id='Names_" + index + "__MiddleName' name='Names[" + index + "].MiddleName' type='text' value='' /> \
</td> \
<td> \
<input class='table-editor-small update-name' data-val='true' data-val-required='Person Last Name Required' id='Names_" + index + "__LastName' name='Names[" + index + "].LastName' type='text' value='' /> \
</td> \
<td class='center'> \
<input data-group='nameRadios' id='Names_" + index + "__IsPrimary' name='Names[" + index + "].IsPrimary' type='radio' value='True' /> \
</td> \
<td class='center'> \
<input data-val='true' data-val-required='The Delete? field is required.' id='Names_" + index + "__ToDelete' name='Names[" + index + "].ToDelete' type='checkbox' value='true' /> \
<input name='Names[" + index + "].ToDelete' type='hidden' value='false' /> \
</td> \
</tr>");
$("#nameTable").append(newItem);
}
同样,要添加的 HTML 直接来自 View 渲染的项目,我只是在 index
关于c# - 从 MVC 中的表单发布列表 <Model>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22489297/