javascript - 如何将 javascript 数组放入 MVC 模型 View 数组中?

标签 javascript c# asp.net asp.net-mvc razor

在一个 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);
}

已填充发布的数据 enter image description here

用于更新隐藏值的 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>

jsFiddle

关于javascript - 如何将 javascript 数组放入 MVC 模型 View 数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29562882/

相关文章:

javascript - 将内容包裹在父元素中

javascript - Node 模块的映射路径,用于单元测试

c# - 将数据更新到asp.net中的gridview中

c# - 在线程之间移动 DependencyObject

asp.net - 来自 ASP.NET MVC 模型数据的 Javascript int 变量?

ASP.NET 缓存对象读写

c# - 将 MVC 应用程序作为子应用程序运行?

javascript - 我如何在 html 和 .js 文件中实现这个 JSFiddle 示例

php - 网站。 AJAX 和 FIREFOX 问题。我认为 Firefox 不喜欢 ajax..?

c# - ASP.NET MVC C# Razor 缩小