Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. Can anybody please tell me how I can achieve that? Thanks

like image 496
user1438482 Avatar asked Dec 13 '12 23:12

user1438482


People also ask

How to store Array in Hidden field in c#?

You could potentially use HttpUtility. HtmlEncode() to escape each string first. Since the HiddenField can only hold string data which is the different type from Array. To store the Array, we need to Serialize the Array to string.

How do you pass an array into a hidden field?

If you want to post an array you must use another notation: foreach ($postvalue as $value){ <input type="hidden" name="result[]" value="$value."> }


3 Answers

Probably a few methods would work.

1) Serialize the String[] in JSON

This would be fairly easy in .NET using the JavaScriptSerializer class, and avoid issues with delimiter characters. 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

Delimit each string with a character such as ||| that will never appear in the string. You can use String.Join() to build this string. 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.

like image 89
Mike Christensen Avatar answered Oct 16 '22 01:10

Mike Christensen


To store the array

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

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

To get the array

string[] myarray = myHiddenField.Value.Split(',');
like image 35
codingbiz Avatar answered Oct 15 '22 23:10

codingbiz


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)
}
like image 35
David Avatar answered Oct 15 '22 23:10

David