【问题标题】:indexing of array from form从表单索引数组
【发布时间】:2021-06-18 12:27:53
【问题描述】:

最近我在从表单发布数据时遇到问题 - 我发送这样的数据:

SamplesAmount[2]: 1
SamplesAsArray[2]: foo
SamplesAmount[1]: 4
SamplesAsArray[1]: bar

然后在模型中我得到没有任何数据的两个变量。即使这些数据不是从 0 开始索引并且它们不包含所有索引(由于删除元素等),是否也可以获得这些数据?

在此先感谢

编辑: Model中变量的定义:

public string[][] SamplesAsArray {get;set;}
public int[] SamplesAmount {get; set;}

【问题讨论】:

    标签: asp.net-core model-binding


    【解决方案1】:

    您可以在表单中添加隐藏输入:(使用Item.Index)

    <input type="hidden" name="SamplesAmount.Index" value="1" />
    <input type="text" name="SamplesAmount[1]" value="4" />
    
    <input type="hidden" name="SamplesAmount.Index" value="2" />
    <input type="text" name="SamplesAmount[2]" value="1" />
    
    <input type="hidden" name="SamplesAsArray.Index" value="1" />
    <input type="text" name="SamplesAsArray[1]" value="bar" />
    
    <input type="hidden" name="SamplesAsArray.Index" value="2" />
    <input type="text" name="SamplesAsArray[2]" value="foo" />
    

    测试结果:

    【讨论】:

      【解决方案2】:

      最后我使用了这个解决方案:

      public Dictionary<int, string[]> SamplesAsArray {get; set;}
      public Dictionary<int, int> SamplesAmount {get; set;}
      

      现在我可以得到任何数字的物品了。

      【讨论】:

        猜你喜欢
        • 2014-11-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-17
        • 1970-01-01
        相关资源
        最近更新 更多