[英]html.textareafor - parse into an array of strings
我在C#MVC(.NET)中,使用@ html.TextAreaFor輸入為字符串存儲的形式,我假設來自此文本框的數據將存儲為字符串,但是我想知道的是用“ / n”元素表示的字符串外觀是否會划定新行標記?
理想情況下,我需要逐行分析文本框,其中每一行上的字符串都成為列表的元素。例如,如果我們在文本框中有
item1
item2
item3
然后,當我提交表單時,將使用文本框中的字符串加載指定的模型,並使用該字符串加載item1,item2和item3的List(在其他模型中的其他位置)。 。
假設您將TextAreaFor
綁定到名為TextAreaModel
的模型屬性,該屬性包含來自用戶輸入的字符串,如下所示:
@model ViewModel
@Html.TextAreaFor(m => m.TextAreaModel, new { ... })
從模型屬性中提取行的正確方法是使用Environment.NewLine
作為POST操作方法中的定界符來分割字符串內容,如下例所示:
[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);
}
注意: StringSplitOptions.RemoveEmptyEntries
將刪除在源字符串中找到的空行,與使用StringSplitOptions.None
相比,我認為這是更推薦的方法。
演示:
相關問題:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.