【问题标题】:How to put javascript array into MVC Model View array?如何将 javascript 数组放入 MVC 模型视图数组中?
【发布时间】:2015-04-10 13:35:26
【问题描述】:

在一个视图中,我在 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; }
}

在视图中我将两个数组都保留为隐藏字段

@html.hiddenfor(model => model.PersonsIds)
@html.hiddenfor(model => model.CompaniesIds)

所以架构看起来像这样:

javascript->model->submit model->controller

任何帮助将不胜感激

【问题讨论】:

  • 所有由 razor 渲染的东西都是一个字符串,所以你需要以某种方式对你的数组进行字符串化,你可以这样做,例如使用 JSON.net (nuget.org/packages/Newtonsoft.Json/6.0.8),然后在 hiddenFor 中渲染该字符串
  • 您也可以坚持使用 asp.net mvc 数组表示法 ("name"="CompaniesIds[index]") 并为 companyId 中的每个 id 呈现隐藏字段,这将使您无需编写自定义活页夹,但会给渲染页面添加很多标记
  • 您可以为 int[] 类型或 UIHint 属性创建编辑器模板...。问题是在回发时,您的自定义字符串将无法在数组中再次解析,因此您需要创建一个自定义模型绑定器,它将获取回发值并将它们存储回一个 int 数组中...我没有任何代码示例...所以我无法为您提供更多帮助。 .. 但这绝对是 MVC 中的做法

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


【解决方案1】:

假设您需要弄清楚如何使模型能够被回发,这就是我的做法。

当您在集合中绑定原始类型时,您只需添加与您的集合同名的输入,模型绑定器就会拾取它们。

举个简单的例子,如果您的视图呈现以下内容:

<input type="hidden" name="PersonsIds" value="1" />
<input type="hidden" name="PersonsIds" value="4" />

这将被回复为:

PersonsIds=1&PersonsIds=4

模型绑定器将拾取它们并将它们转换为整数集合。

这是一个简单的示例,可以查看模型绑定与虚拟数据的作用,您只需在回发之前使用 javascript 呈现隐藏的值。

查看

@using (Html.BeginForm())
{
    foreach(var personId in Model.PersonsIds)
    {
        @Html.Hidden("PersonsIds", personId)
    }

    <input type="submit" value="submit" >
}

控制器

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>

jsFiddle

【讨论】:

    【解决方案2】:
    @model AppointmentModel
    
    @for(var i = 10; i < model.PersonsIds.Length; i++)
    {<p>Line 
        @html.hiddenfor(model => model.PersonsIds[i])
    </p>}
    

    例如

    @for (int i = 0; i < Model.Count; i++)
    {
        @Html.HiddenFor(x=>Model[i].Id) @Model[i].Name  
        @Html.TextBoxFor(x => Model[i].Quantity) <br/>
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-03
      • 1970-01-01
      • 2011-02-20
      • 1970-01-01
      • 2019-01-26
      • 1970-01-01
      • 1970-01-01
      • 2021-11-01
      相关资源
      最近更新 更多