简体   繁体   English

在HiddenField asp.net中存储字符串数组

[英]storing an array of strings in a HiddenField asp.net

I need to store an array of string in a HiddenField in my webform with asp.net. 我需要使用asp.net在我的webform中的HiddenField中存储一个字符串数组。 Can anybody please tell me how I can achieve that? 请问有谁可以告诉我如何实现这一目标? Thanks 谢谢

Probably a few methods would work. 可能有一些方法可行。

1) Serialize the String[] in JSON 1)在JSON中序列化String []

This would be fairly easy in .NET using the JavaScriptSerializer class, and avoid issues with delimiter characters. 这在使用JavaScriptSerializer类的.NET中相当容易,并且避免了分隔符字符的问题。 Something like: 就像是:

String[] myValues = new String[] { "Red", "Blue", "Green" };
string json = new JavaScriptSerializer().Serialize(myValues);

2) Come up with a delimiter that never appears in the strings 2)想出一个从未出现在字符串中的分隔符

Delimit each string with a character such as ||| |||等字符分隔每个字符串 that will never appear in the string. 永远不会出现在字符串中。 You can use String.Join() to build this string. 您可以使用String.Join()来构建此字符串。 Something like: 就像是:

String[] myValues = new String[] { "Red", "Blue", "Green" };
string str = String.Join("|||", myValues);

And then rebuild it like: 然后重建它像:

myValues = str.Split(new string[] { "|||" }, StringSplitOptions.RemoveEmptyEntries);

This might be the best option if you can trust your input, such as a series of numbers of pre-defined choices. 如果您可以信任您的输入,这可能是最佳选择,例如一系列预定义的选择。 Otherwise, you'd probably want to check your input strings to make sure they don't contain this delimiter if you wanted to be very safe. 否则,您可能想要检查输入字符串,以确保它们不包含此分隔符,如果您想要非常安全。 You could potentially use HttpUtility.HtmlEncode() to escape each string first. 您可以使用HttpUtility.HtmlEncode()来首先转义每个字符串。

To store the array 存储数组

string[] myarray = new string[] {"1","2"};

myHiddenField.Value = String.Join(",", myarray);

To get the array 获得阵列

string[] myarray = myHiddenField.Value.Split(',');

Do you actually want to store it in a single field? 你真的想把它存放在一个字段中吗?

If you put each value in it's own hidden field, and give all the hidden fields the name of your property then the model binding will treat this as an array. 如果将每个值放入其自己的隐藏字段中,并将所有隐藏字段赋予属性名称,则模型绑定会将其视为数组。

foreach (var option in Model.LookOptions)
{
    @Html.Hidden(Html.NameFor(model => model.LookOptions).ToString(), option)
}

Existing Answers 现有答案

I'd always rather use the default property and model binder than having to wrap an array into a CSV and having to worry about splitting it and joining it on every single round trip to the client (as in the answers by @Mike Christensen and @codingbiz ). 我总是宁愿使用默认属性和模型绑定器而不是将数组包装成CSV并且不得不担心拆分并在每次往返客户端时加入它(如@Mike Christensen@的答案) codingbiz )。 This is exactly what the model binder is there for. 这正是模型绑定器的用途。

@David's answer points us in the right direction, but I'd rather not inline that type of logic into your view and relegate it to an EditorTemplate instead. @ David的回答指出了我们正确的方向,但我不想在你的视图中将这种类型的逻辑内联,而是将其转换为EditorTemplate。

Preferred Solution 首选方案

So you can add the following view ~/Views/Shared/EditorTemplates/HiddenArray.cshtml 所以你可以添加以下视图~/Views/Shared/EditorTemplates/HiddenArray.cshtml

@model Array

@foreach (var value in Model)
{
    <input type="hidden" value="@value"
           name="@Html.NameFor(model => model)"
           id="@(Html.IdFor(model => model))_@value" />
}

Then call like this from your model: 然后从你的模型中这样调用:

@Html.EditorFor(model => model.FavoriteAnimals, "HiddenArray")

Alternative Strategies 替代策略

Here's how I arrived at manually specifying the name and id variable for each hidden input: 这是我如何手动指定每个隐藏输入的名称和id变量:

隐藏数组

  • A) Can't use HiddenFor() inside a loop because it thinks the property name now includes the value A)不能在循环中使用HiddenFor()因为它认为属性名称现在包含值
  • B) When we call EditorFor, the current model is added to the Route Prefix so if we pass the current model name as a string to to Hidden() we'll actually double up and the property name won't be able to bind on the way back. B)当我们调用EditorFor时,当前模型被添加到Route Prefix中,所以如果我们将当前模型名称作为字符串传递给Hidden()我们实际上会加倍并且属性名称将无法绑定回去的路。
  • C) It feels odd, but we can just pass an empty string as the name and rely on the Route Prefix to do its job, but because we're inside a loop, the ID that gets produced isn't valid HTML C)感觉很奇怪,但是我们可以只传递一个空字符串作为名称并依赖Route Prefix来完成它的工作,但因为我们在一个循环中,所产生的ID是无效的HTML
  • D) By grabbing the name and ID from the model and incrementing the dummy ID, we can continue to output valid HTML, even though it's probably not likely to affect anything but html linters and audits D)通过从模型中获取名称和ID并递增虚拟ID,我们可以继续输出有效的HTML,即使它可能不会影响除html linters和audit之外的任何内容

Further Reading: 进一步阅读:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM