Kurkula Kurkula - 7 days ago 9
ASP.NET (C#) Question

Asp.net mvc Razor fill values to textarea from text file

I am trying to read a text file and fill those values in a text area. What is my mistake here

@{
var dataFile = Server.MapPath("~/Files/myFile.txt");
var ListFromFile= File.ReadAllLines(dataFile);
@Html.TextArea("name", "", ListFromFile)
}
<textarea>
@ListFromFile.ToList();
</textarea>

Answer

You cannot directly set list as textarea value.So, you need to build a string.

You have to use the StringBuilder class for concatenating many strings together in a loop.

Please try this:

@{
    var dataFile = Server.MapPath("~/Files/myFile.txt");
    var ListFromFile= File.ReadAllLines(dataFile);
    StringBuilder sb = new StringBuilder();
    foreach (string line in ListFromFile)
    {
       sb.Append(line + "\n");   
    }
    var str = new HtmlString(sb.ToString());
}

Then set textarea value:

<textarea>@Html.Raw(str)</textarea>

Or simply:

<textarea>@str</textarea>

Another method is to use String.Join

@{
    var dataFile = Server.MapPath("~/Files/myFile.txt");
    var ListFromFile= File.ReadAllLines(dataFile);
    var str = String.Join("\n", ListFromFile.ToArray());
}
<textarea>@str</textarea>
Comments