1

我是 mvc 的新手。我有一个有两种方法的控制器。我想通过单击按钮将列表返回到文本文件。我一直在尝试找出如何将列表传递给 CreateReportFile 方法的方法,但没有运气。它适用于 stringbuilder 对象。

您知道如何在文本文件中显示列表吗?

@Html.ActionLink("Download File", "CreateReportFile");


         public FileStreamResult CreateReportFile()
                {
                    //todo: add some data from your database into that string:
                    var string_with_your_data = string.Empty;              
                    var byteArray = Encoding.ASCII.GetBytes(string_with_your_data);
                    var stream = new MemoryStream(byteArray);
                    return File(stream, "text/plain", "Report" + DateTime.Now + ".txt");
                }



                public List<Student> GetStudents()
                {
                    return new List<Student>()
                    {
                        new Student() {firstname="james",lastname="john",emailAddress="james.john@yahoo.com"},
                        new Student() {firstname="patric",lastname="swayze",emailAddress="patric.swayze@yahoo.com"},
                        new Student() {firstname="james",lastname="john",emailAddress="james.john@yahoo.com"},
                        new Student() {firstname="toy",lastname="gas",emailAddress="toy.gas@yahoo.com"}
                    };
                }
4

3 回答 3

3

如果您试图将学生列表放入您正在写入文件的字符串中,您可以尝试:

public FileStreamResult CreateReportFile()
{
    List<Student> students = GetStudents();
    StringBuilder sb = new StringBuilder();
    foreach (Student s in students)
        sb.AppendLine(s.firstname + ", " + s.lastname + ", " + s.emailAddress);

    var string_with_your_data = sb.ToString();
    var byteArray = Encoding.ASCII.GetBytes(string_with_your_data);
    var stream = new MemoryStream(byteArray);
    return File(stream, "text/plain", "Report" + DateTime.Now + ".txt");
}
于 2013-10-10T16:40:49.757 回答
0

您所要做的就是添加它以使其成为字符串,然后发送数据。

 foreach(Student test in GetStudents())
            {
                string_with_your_data += test.firstname + ", " + test.lastname + ", " + test.emailAddress + "\r\n";
            }
于 2013-10-10T16:43:38.577 回答
0

如果您询问如何将 List 对象转换为文本,则需要创建一个方法来执行此操作,或者您可以使用 Serializer,但这会将其格式化为 json 或 xml。

要在学生对象中自己转换对象,您可以使用以下内容覆盖 ToString:

public override string ToString()
{ 
    return String.Format("firstname={0}, lastname={1}, emailAddress={2}", firstname, lastname, emailAddress);
}

然后你可以遍历你的列表

string mystring = string.Empty;
foreach(var student in Students)
     mystring += student.ToString() + "\n";

只是一些可能让你开始的想法。

于 2013-10-10T16:45:36.650 回答