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
相关问题
- Carriage Return (ASCII chr 13) is missing from tex
- How to store image outside of the website's ro
- 'System.Threading.ThreadAbortException' in
- Request.PathInfo issues and XSS attacks
- How to dynamically load partial view Via jquery aj
相关文章
- asp.net HiddenField控件扩展问题
- asp.net HiddenField控件扩展问题
- Asp.Net网站无法写入错误日志,测试站点可以,正是站点不行
- asp.net mvc 重定向到vue hash字符串丢失
- FormsAuthenticationTicket expires too soon
- “Dynamic operations can only be performed in homog
- What is the best way to create a lock from a web a
- Add to htmlAttributes for custom ActionLink helper
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.
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). 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.
Preferred Solution
So you can add the following view
~/Views/Shared/EditorTemplates/HiddenArray.cshtml
Then call like this from your model:
Alternative Strategies
Here's how I arrived at manually specifying the name and id variable for each hidden input:
HiddenFor()
inside a loop because it thinks the property name now includes the valueHidden()
we'll actually double up and the property name won't be able to bind on the way back.Further Reading:
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: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 useString.Join()
to build this string. Something like:And then rebuild it like:
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.To store the array
To get the array