Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding TEXTAREA to List<string>

I have a textarea bound to List<string> in the data model.

I find that the content entered in the control is returned as one long string, with \r\n at line breaks, in the only element in the List<string>.

Is it possible for each line to be automatically returned as each element in the List<string>?

like image 863
Old Geezer Avatar asked Oct 15 '25 19:10

Old Geezer


1 Answers

Yes it is possible, by writing a custom model binder. However as GregH says in the comments it may be simpler to split the string at new lines only where required at the back end...

If a textarea is suitable and convenient from a UI perspective, that's great. In that case I would argue that you stick with default model binder and only convert to List<string> when required (such as db insert).

Otherwise a dynamic list of inputs is possible with some javascript - an add input button. These 1-to-n input elements will be picked up by the default model binder in to a List<string> automatically just by using the same attribute name on the input element. See Model binding to a list

There are only two html elements of relevance here: textarea and input. The difference between them is that a textarea natively allows for multi-line (text-wrapping and/or line breaks) whereas input must not. Pressing enter in a text area creates a new line whereas pressing enter in an input submits the entire form.

like image 159
Khyron Avatar answered Oct 18 '25 23:10

Khyron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!