将值从文本文件打印到文本区域

时间:2017-04-27 15:14:05

标签: c# asp.net asp.net-mvc

所以我第一次尝试提问这个问题是愚蠢的 - 我道歉

所以我正在阅读文本文件的内容 - 这只是数字行。我试图计算每一行的总和,并按降序单独打印出答案。

以下是我的控制器中的代码:

 public void ReadFromText()
    {
        Array LogFileData = null;

        var logFileNameWithPath = Server.MapPath(@"~/Docs/Q1InputFile.txt");

        if (System.IO.File.Exists(logFileNameWithPath))
        {
            LogFileData = System.IO.File.ReadAllLines(logFileNameWithPath);

            foreach (var line in LogFileData)
            {
                //code goes here
            }
        }


        ViewBag.logFileContent = LogFileData;


    }

我正在努力将文本文件中的内容发送到文本区域并使用for each来计算每行的总和。

以下是视图的代码:

<h2>Question1</h2>

<div class="jumbotron">    
<p class="lead">Please click the button to load the results</p>    
<input type="button" title="LoadAnswer" value="Click me" id ="btn_run") 
onclick="location.href='@Url.Action("ReadFromText", "Question1")'" />   
@if (ViewBag.logFileContent != null) 
{
foreach (string dataLine in ViewBag.logFileContent) 
{
    @dataLine
    <br /> 
    } 
  }   
</div>

@Html.TextArea("ReadFromText", "Question1")

<div>
@Html.ActionLink("Back to Home", "Index", "Home")
</div>

对不起,这是一个基本问题 - 但我是新手,并试图从中吸取教训 请指教

3 个答案:

答案 0 :(得分:0)

假设您的按钮是html并且在客户端的浏览器中,并且文件位于解决方案目录中的服务器上(不在客户端)

我会关注

  1. 当按下浏览器中的按钮时,我将向服务器发出ajax调用。
  2. 在服务器上,控制器会打开一个文件流到这个文件,逐个读取行或者你想用它们做什么,然后以json格式发送输出。
  3. 当服务器将输出返回给ajax响应时,我将用该响应替换文本区域,或者在需要时附加它。
  4. 所有这三个步骤都可以通过测试数据单独完成。我首先创建一个ajax测试,然后在控制器上返回一个数字,然后使用js在文本字段中填充它。完成后,您只需要在控制器中处理文件读取功能,并返回文件中的内容或文件中的总和等。

答案 1 :(得分:0)

点击按钮进行AJAX通话

示例Ajax代码:

$.ajax({
type : 'POST',
url : '@Url.Action("your controller and actions goes here")',
dataType : 'json',
data : {
    //Send file path if it is dynamic
},
success : function (data) {
    //Logic to format and display your text file data
},
error : function (ex) {}
});

C# - 服务器端代码:

string text;
var fileStream = new FileStream(@"c:\file.txt",FileMode.Open,FileAccess.Read);
using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
{
   text = streamReader.ReadToEnd();
}

将JSON格式的文本发送到客户端,并根据您的要求显示

请参阅此链接以了解AJAX实施http://dotnetmentors.com/mvc/jquery-ajax-call-with-jsonresult-in-asp-net-mvc.aspx

答案 2 :(得分:0)

我知道为时已晚,但我现在看到了您的问题。 我更喜欢从txt文件中逐行读取,然后创建一个stringBuilder并将其发送到这样的textare元素,希望对您有所帮助。

List<string> linesFromFile= File.ReadAllLines(filePath).ToList();
StringBuilder str = new StringBuilder();
foreach (string item in linesFromFile)
{
     str.AppendLine(item);
}
ViewBag.RobotsTxt = str;