简体   繁体   中英

html.textareafor - parse into an array of strings

I am in C# MVC (.NET) and have a form where I have input with @html.TextAreaFor stored as a string I am assuming that the data from this text box will store as a string, but what I am wondering is how will the string look, in terms of "/n" elements, will the string delimit new line markers?

Ideally, I need to parse the textbox line-by-line, where the string on each line becomes an element of a List For example, if we have in the textbox

  item1
  item2
  item3

Then when I submit the form, the model that I specified will be loaded with the string form the textbox, and using that string we will load up our List (somewhere else, in a different model..)with item1, item2, and item3.

Suppose you have TextAreaFor bound to a model property named TextAreaModel which contains strings from user input like this:

@model ViewModel

@Html.TextAreaFor(m => m.TextAreaModel, new { ... })

The proper way to extract lines from model property is splitting the string content using Environment.NewLine as delimiter in POST action method as shown in example below:

[HttpPost]
public ActionResult SubmitForm(ViewModel model)
{
    // other stuff   

    // parse every textarea lines as list elements
    List<string> list = model.TextAreaModel.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).ToList();

    // assign it to other list property on other model
    OtherModel.OtherList = list;

    // other stuff

    return View(model);
}

NB: StringSplitOptions.RemoveEmptyEntries will remove empty lines found in source string, which I think this is more recommended way than using StringSplitOptions.None .

Demos:

.NET Fiddle Example - Splitting By Newline

.NET Fiddle Example - MVC Implementation

Related issue:

How to parse user input from a textarea line by line

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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