Mvc:通过单击按钮</student>在文本文件中显示数据库中的List <student>

时间:2013-10-10 16:24:31

标签: c#

我是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"}
                    };
                }

3 个答案:

答案 0 :(得分: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");
}

答案 1 :(得分:0)

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

 foreach(Student test in GetStudents())
            {
                string_with_your_data += test.firstname + ", " + test.lastname + ", " + test.emailAddress + "\r\n";
            }

答案 2 :(得分: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";

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