如何将结果导入视图

时间:2013-11-05 04:08:29

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

我是C#的新手。如何在Razor视图中显示SQL?

// GET: /ReportData
public ActionResult Index()
{
    using (SqlConnection connection = new SqlConnection(@"Data Source=xxx.xxx.xxx.xxx;Initial Catalog=xxxxxx;Persist Security Info=True;User ID=xxxxx;Password=xxxxx"))
    {
        using (SqlCommand command = connection.CreateCommand())
        {
            command.CommandText = @"select * from ProjectManagement as p 
            join Implementation as i on p.JobNumber = i.JobNumber 
            join Divisions as d on i.Division = d.Division 
            where p.ProjectStatus = 'Active'"

            connection.Open();
            using (SqlDataReader reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    // process result
                    reader.GetValue(0);
                    reader.GetValue(1);
                    reader.GetValue(2);
                    reader.GetValue(3);
                    reader.GetValue(4);
                    reader.GetValue(5);
                }

            }
        }
    }         

    return View();
}    

我理解这取决于读者对象但在此之后我不知道如何继续。只需要要点...

1 个答案:

答案 0 :(得分:0)

您确实需要查看实体框架并进入建模。这个问题需要很多答案。

Microsoft的EF(实体框架)http://msdn.microsoft.com/en-us/data/ef.aspx 或者当然使用stackoverflow并使用剃刀查找实体框架和视图模型。

上面的答案假设你正在使用它,并且不适用于你正在做的循环数据库的旧方法。这真的不是一个很好的答案,但你有一些关于实体框架或其他ORM(对象关系映射器)的研究,这应该让你去。

// GET: /ReportData
public ActionResult Index()
{
    List<DataHolder> data = new List<DataHolder>();
    using (SqlConnection connection = new SqlConnection(@"Data Source=xxx.xxx.xxx.xxx;Initial Catalog=xxxxxx;Persist Security Info=True;User ID=xxxxx;Password=xxxxx"))
    {

        using (SqlCommand command = connection.CreateCommand())
        {
            command.CommandText = @"select * from ProjectManagement as p 
            join Implementation as i on p.JobNumber = i.JobNumber 
            join Divisions as d on i.Division = d.Division 
            where p.ProjectStatus = 'Active'"

            connection.Open();
            using (SqlDataReader reader = command.ExecuteReader())
            {                  
                while (reader.Read())
                {
                   data.Add( new DataHolder {
                      Item1 = reader.GetValue(0),
                      Item2 = reader.GetValue(1)
                   });
                    // process result
                    //reader.GetValue(0);
                    //reader.GetValue(1);
                    //reader.GetValue(2);
                    //reader.GetValue(3);
                    //reader.GetValue(4);
                    //reader.GetValue(5);
                }

            }
        }
    }         

    return View(data);
}


public class DataHolder {
  public string Item1 { get; set; }
  public string Item2 { get; set; }
}

然后在view.cshtml中

@model List<DataHolder>

@foreach(var a in Model) {
  <p>@a.Item1 @a.Item2</p>
}