I have a .txt file and I should scroll and print each element on the screen (list of strings). I am new and inexperienced, can you please help me write the file ndex.cshtml (view)?
(Class.cs)
public class Reader
{
public static List<string> Read(string path)
{
var result = new List<string>();
String line;
try
{
StreamReader sr = new StreamReader(path);
line = sr.ReadLine();
while (line != null)
{
result.Add(line);
line = sr.ReadLine();
}
}
catch (Exception e)
{
result = new List<string>();
}
return result;
}
}
}
(HomeController.cs) {
public class HomeController : Controller
{
public ActionResult Index()
{
var result = Reader.Reader.Read("......txt");
return View(result);
}
CodePudding user response:
Depending on how you want to render the view...
View.cshtml
You can specify a List as your type of model if you wish instead of introducing your own abstractions. Here is a partial view:
@model List<string>
@{
Layout = null;
}
<ul>
@{
foreach (string line in Model)
{
<li>@line</li>
}
}
</ul>
In the razor view you can iterate through the strings in the foreach. Here I'm putting the output in an unordered list.
You can add c# code to execute in the view using the @ blocks. @{ } will put in a block of code to execute.
Reading text file
You can also read all lines from the text file using:
string[] lines = System.IO.File.ReadAllLines(@"...filename.txt");
Putting the full path to the filename. Then you could change your type of model to Enumerable<string> as we are only enumerating through the collection.
CodePudding user response:
I just created a demo project in github, to display text lines in html. The OP also mentioned scroll and print, but that should be considered only after succcesfully display those lines. So this demo can be a start for the OP. Also paste main code here. I'm using Razor pages.
- Code behind
public class IndexModel : PageModel
{
//other lines...
public string[] Lines { get; set; }
public void OnGet()
{
// you need change the fullName, and may need some exception handling
string fullName = Path.Combine(_hostEnvironment.WebRootPath, "js/site.js");
Lines = System.IO.File.ReadAllLines(fullName);
}
}
- Razor
<div >
<h1 >This is text lines</h1>
@foreach (string line in @Model.Lines)
{
<p>@line</p>
@*add a hr to distinguish lines*@
<hr />
}
</div>
