无法将数据从数据库表传递到视图

时间:2015-08-03 14:14:59

标签: c# asp.net-mvc entity-framework viewmodel

我使用查询填充SQL表,然后尝试将模型(对于表)中的数据传递到视图中。我试图使用ViewModel将数据传递给Controller Action中的视图。

以下是模型:

    public partial class Report
{
    public int Id { get; set; }
    public string Number { get; set; }
    public Nullable<decimal> Amount { get; set; }
    public Nullable<System.DateTime> Date { get; set; }
    public Nullable<int> ReasonId { get; set; }
    public string Notes { get; set; }
}

IEnumerable ViewModel:

public class ReportViewModel
{
    public IEnumerable<Report> Reports { get; set; }
}

控制器操作:

        [HttpPost]
    public ActionResult UploadValidationTable(HttpPostedFileBase csvFile)
    {
        //Unrelated Code to read a CSV into another database table goes here
        //But was removed so it wouldn't be confusing.


        var db = new Report();

        var reportModel = new ReportViewModel()
        {
            Reports = new List<Report>() {new Report()}
        };

        return View("Upload", reportModel);
    }

查看:

@model Entities.Models.ReportViewModel

                    <table class="table">
            <thead>
            <tr>
                <th>Id</th>
                <th>Number</th>
                <th>Amount</th>
                <th>Date</th>
                <th>Reason Id</th>
                <th>Notes</th>
            </tr>
            </thead>
                    <tbody>
                    @if (Model != null)
                    {
                        foreach (var item in Model.Reports.Where(x => x.Id != null))
                        {
                            <tr>
                                <td>
                                    @item.Id
                                </td>
                                <td>
                                    @item.Number
                                </td>
                                <td>
                                    @item.Amount
                                </td>
                                <td>
                                    @item.Date
                                </td>
                                <td>
                                    @item.ReasonId
                                </td>
                                <td>
                                    @item.Notes
                                </td>
                            </tr>
                        }
                    }
                    </tbody>
        </table>

但是当我尝试返回View时出现异常,其中ReportViewModel无法分配给模型类型IEnumerable ReportViewModel

所以我只是试图将报表数据库中的所有行传递到我视图中的HTML表。任何帮助,或更好的方式来做到这一点将不胜感激。

0 个答案:

没有答案