4

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>?

Old Geezer
  • 14,854
  • 31
  • 111
  • 198
  • I think you could split on new line on the controller side when the data is posted back. You also may be able to implement a custom html helper to help you with this. Are you able to elaborate on the use case at all? It seems a bit strange to me to be using a textarea like this – GregH Jan 09 '19 at 13:08
  • My `textarea` is used to let the user enter lines of data to be submitted for processing. Is there another Html control more suitable for multi-line inputs? – Old Geezer Jan 09 '19 at 13:37
  • 1
    Seems like it may be more suitable to have individual text inputs if the lines of the input need to be handled individually. By virtue of needing to split on new line, it doesn't really seem like you want multi-line input which is why I was asking. If you need to do this, I think you're best bet will be to split on new line on the controller side – GregH Jan 09 '19 at 13:42
  • The number of lines the user can enter varies, so difficult to have mutliple ``s. I was hoping that as it could be bound to `List` it would also return as individual elements in `List`. – Old Geezer Jan 09 '19 at 13:57

1 Answers1

2

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.

Khyron
  • 468
  • 3
  • 11