在视图文件的表中显示数据库行

时间:2015-05-04 15:59:07

标签: asp.net asp.net-mvc razor

基本上,我在解析View文件中的某些数据时遇到了麻烦,这些数据是从控制器发送的。

我是ASP.NET MVC的新手,我使用的是Razor,我相信它是网页的一部分。

所以下面我有一些代码,我试图在我的视图文件中放入一个表,它基本上只是在这种情况下来自我的数据库的请求。目前这将获得12行数据,我想将这些数据管理到表格中。

var requests = Database.Open("SQLServerConnectionString").Query("SELECT * FROM Requests");
                model.requests = from o in requests
                             select new { RequestId = o.RequestId, UserId = o.UserId, ModuleId = o.ModuleId, no_rooms = o.no_rooms, Parks = o.Parks, Rooms = o.Rooms, Weeks = o.Weeks, Day = o.Day, Semester = o.Semester, StartTime = o.StartTime, EndTime = o.EndTime, Length = o.Length, Students = o.Students, Type = o.Type, Priority = o.Priority, Comments = o.Comments, Facilities = o.Facilities, Status = o.Status, Round = o.Round, DateSubmitted = o.DateSubmitted, Year = o.Year };

现在在我的视图文件中,我基本上都在尝试做这样的事情

@foreach (var request in Model.requests)
{
  <tr>
    @request.RequestId 
  </tr>
}

现在,如果我这样做,我会收到以下构建错误:

An exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in System.Core.dll but was not handled in user code

Additional information: 'object' does not contain a definition for 'RequestId'

现在,请求的模型定义如下:

public IEnumerable<dynamic> requests { get; set; }

请注意,如果我只做了@request而不是@request.RequestId,我会为每一行获得以下输出:

{ RequestId = 1, UserId = 1, ModuleId = 1, no_rooms = 3, Parks = Central,Central,Central, Rooms = 1,2,3, Weeks = 1, Day = 1, Semester = 1, StartTime = 09:00, EndTime = 13:00, Length = 4, Students = 179, Type = Booking, Priority = P, Comments = , Facilities = 1, Status = 1, Round = 1, DateSubmitted = 11/03/2015 21:59:22, Year = 2015/2016 }

如何制作,以便将行输出到视图文件中的表格中?

1 个答案:

答案 0 :(得分:1)

如果“要求”是您要传递给视图的模型,那么您的视图应如下所示:

@model IEnumerable<ApplicationName.Models.Request>

// table
<table>
  <tr>
    <th>Request ID</th>
  </tr>
  @foreach (var request in Model)
  {
    <tr>
      <td>@request.RequestId</td>
    </tr>
  }
</table>

如果您的项目中没有针对请求的强类型模型,则可能值得创建一个。

public class Request
{
  public int RequestId { get; set; }
  public int UserId { get; set; }
  public int ModuleId { get; set; }
  public int no_rooms { get; set; }
  public string Parks { get; set; }
  etc...
}