在一个 View 中,我在 javascript 中创建了一个包含元素 ID 的数组,现在我想将它们传递到我的 MVC 模型中的模型字段中,有人已经遇到过这种问题吗,这是我的模型:
public class AppointmentModel
{
public int Id { get; set; }
public string Title { get; set; }
public int[] PersonsIds { get; set; }
public int[] CompaniesIds { get; set; }
}
在 View 中我将两个数组都保留为隐藏字段
@html.hiddenfor(model => model.PersonsIds)
@html.hiddenfor(model => model.CompaniesIds)
所以架构看起来像这样:
javascript->model->submit model->controller
如有任何帮助,我们将不胜感激
最佳答案
假设您需要弄清楚如何使模型回发,这就是我会做的。
当您在集合中绑定(bind)原始类型时,您只需添加与集契约(Contract)名的输入,模型绑定(bind)器就会将它们拾取。
举个简单的例子,如果您的 View 呈现以下内容:
<input type="hidden" name="PersonsIds" value="1" />
<input type="hidden" name="PersonsIds" value="4" />
这将被发回:
PersonsIds=1&PersonsIds=4
模型绑定(bind)器将拾取它们并将它们转换为整数集合。
这里是一个简单的示例,用于查看模型绑定(bind)与虚拟数据的作用,您只需要在回发之前使用 javascript 呈现隐藏值。
查看
@using (Html.BeginForm())
{
foreach(var personId in Model.PersonsIds)
{
@Html.Hidden("PersonsIds", personId)
}
<input type="submit" value="submit" >
}
Controller
public ActionResult Index()
{
return View(new AppointmentModel { PersonsIds = new int[] { 1, 4 } });
}
[HttpPost]
public ActionResult Index(AppointmentModel model)
{
return View(model);
}
已填充发布的数据
用于更新隐藏值的 Javascript
<input type="text" id="IdToAdd" />
<button >Add</button>
<input type="hidden" name="PersonsIds" value="1" />
<input type="hidden" name="PersonsIds" value="4" />
<script>
$(function() {
$('button').click(function() {
$(this).after('<input type="hidden" name="PersonIds" value="' + $('#IdToAdd').val() + '" />');
});
});
</script>
关于javascript - 如何将 javascript 数组放入 MVC 模型 View 数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29562882/