微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

C# MVC 返回 ViewModel 到列表

如何解决C# MVC 返回 ViewModel 到列表

我决定发布一个新问题而不是添加到现有问题中,因为这不是同一个问题。我按照另一个问题的评论创建了一个 viewmodel。

到目前为止,我还没有从 viewmodel 中列出。我确实在网上搜索过,看看我是否能找到一个例子,但我发现的只是;如何在 viewmodel 中创建列表,我已经知道该怎么做了。

我在下面有一个 viewmodel。我不确定它的结构是否正确,但控制器正在返回 count = 0

控制器:

    public ActionResult Index()
    {
        List<Accountingviewmodels> list = new List<Accountingviewmodels>();
        return View(list);
    }

视图具有:@model IEnumerable<BestenEquipment.Models.Accountingviewmodels>

我确实尝试过@model List<BestenEquipment.Models.Accountingviewmodels>

但出现错误 'List<Accountingviewmodels>' does not contain a deFinition for 'Description' and no extension method 'Description' accepting a first argument of type 'List<Accountingviewmodels>' Could be found (are you missing a using directive or an assembly reference?)

控制器仍然是 count = 0

IEnumerable 不会出错,它只是给了我一个空表。所以我认为 IEnumerable 是要走的路。我只需要修复控制器。

如果有人能指出我正确的方向或告诉我我的控制器有什么问题,那将大有帮助。

这是视图模型:

public class Accountingviewmodels
{
    [Key]
    public Guid TransactionId { get; set; }
    public string Description { get; set; }
    [display(Name = "Company")]
    public int? CompanyId { get; set; }
    [display(Name = "vendor")]
    public Guid? vendorId { get; set; }
    [display(Name = "Rec Chk #")]
    public string InCheckNumber { get; set; }
    [display(Name = "Sent Chk #")]
    public string OutCheckNumber { get; set; }
    [display(Name = "Invoice #")]
    public string InvoiceNumber { get; set; }
    [display(Name = "PO #")]
    public string PurchaSEOrderNumber { get; set; }
    [display(Name = "Ledger Acct")]
    public Guid LedgerAccountId { get; set; }
    [display(Name = "Credit")]
    public decimal? DebitAmount { get; set; }
    [display(Name = "Debit")]
    public decimal? CreditAmount { get; set; }
    [display(Name = "Transaction")]
    [displayFormat(DataFormatString = "{0:MM/dd/yyyy}",ApplyFormatInEditMode = false)]
    public DateTime TransactionDate { get; set; }
    [display(Name = "Modified By")]
    public string ModifiedBy { get; set; }
    [display(Name = "Modified")]
    [displayFormat(DataFormatString = "{0:MM/dd/yyyy}",ApplyFormatInEditMode = false)]
    public DateTime? ModifiedDate { get; set; }
    public string SavedDocument { get; set; }
    [display(Name = "Created")]
    [displayFormat(DataFormatString = "{0:MM/dd/yyyy}",ApplyFormatInEditMode = false)]
    public DateTime CreatedDate { get; set; }
    [display(Name = "Created By")]
    public string CreatedBy { get; set; }
    public bool IsCredit { get; set; }
    public bool IsDebit { get; set; }
    public Guid Type { get; set; }

    [ForeignKey("LedgerAccountId")]
    public LedgerAccount LedgerAccount { get; set; }
    [ForeignKey("CompanyId")]
    public CompanyNames Company { get; set; }
    [ForeignKey("vendorId")]
    public vendors vendor { get; set; }
}

这很可能是一个简单的修复,我只需要轻轻一推..

使用db模型是这样的:return View(db.Transaction.ToList());

我需要用 viewmodel 做同样的事情..

感谢您的帮助!

谢谢

更新:

这是我的原始问题的链接,并被告知要创建一个视图模型.. Original Issue

更新:

添加视图:

@model List<BestenEquipment.Models.Accountingviewmodels>
@{
   Layout = "~/Views/Shared/_DashboardLayout.cshtml";
}


@section ScriptsOrCss
{
    @Html.Action("DataTableCssjs","Layout")
}
@Html.ValidationSummary(true,"",new { @class = "text-danger" })

<section class="content-header">
<h1>
    Overview List
    <small> Transactions </small>
</h1>
</section>
<section class="content">
<!-- Small Boxes (Stat Box) -->
<div class="row">
    <div class="col-md-12">
        @if (ViewBag.Create == true)
        {
            <div class="Box Box-solid Box-primary">
                <div class="Box-body">
                    <!-- Split button -->
                    <div class="margin">
                        <div class="btn-group">
                            @Ajax.ModalDialogActionLink("Create Quick","Create","Create ","btn btn-info btn-sm")
                        </div>
                        <div class="btn-group">
                            <a href="~/Tranaction/Create" class="btn btn-warning btn-sm">Create Full</a>
                        </div>
                    </div>
                    <!-- flat split buttons -->
                </div><!-- /.Box-body -->
            </div>
        }

        <div class="Box Box-primary">
            <div class="Box-header">
                <h3 class="Box-title">Orders</h3>
            </div><!-- /.Box-header -->
            <div class="Box-body table-responsive">
                <table class="table table-striped table-hover table-bordered" id="TransactionListTable">
                    <thead>
                        <tr>
                            <th>
                                @Html.displayNameFor(model => model.Description)
                            </th>
                            <th>
                                @Html.displayNameFor(model => model.Company.CompanyName)
                            </th>
                            <th>
                                @Html.displayNameFor(model => model.vendor.Name)
                            </th>
                            <th>
                                @Html.displayNameFor(model => model.InCheckNumber)
                            </th>
                            <th>
                                @Html.displayNameFor(model => model.OutCheckNumber)
                            </th>
                            <th>
                                @Html.displayNameFor(model => model.InvoiceNumber)
                            </th>
                            <th>
                                @Html.displayNameFor(model => model.PurchaSEOrderNumber)
                            </th>
                            <th>
                                @Html.displayNameFor(model => model.LedgerAccountId)
                            </th>
                            <th>
                                @Html.displayNameFor(model => model.DebitAmount)
                            </th>
                            <th>
                                @Html.displayNameFor(model => model.CreditAmount)
                            </th>
                            <th>
                                @Html.displayNameFor(model => model.TransactionDate)
                            </th>
                            <th>
                                CRUD
                            </th>
                            <th>
                                Actions
                            </th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach (var item in Model.Items)
                        {
                        <tr>
                            <td>
                                @Html.displayFor(modelItem => item.Description)
                            </td>
                            <td>
                                @if (item.CompanyId != null)
                                {
                                    @Html.displayFor(modelItem => item.Company.CompanyName)
                                }
                                else
                                {
                                    <b>N/A</b>
                                }

                            </td>
                            <td>
                                @if (item.vendorId != null)
                                {
                                    @Html.displayFor(modelItem => item.vendor.Name)
                                }
                                else
                                {
                                    <b>N/A</b>
                                }

                            </td>
                            <td>
                                @if (item.InCheckNumber != null)
                                {
                                    @Html.displayFor(modelItem => item.InCheckNumber)
                                }
                                else
                                {
                                    <b>N/A</b>
                                }
                            </td>
                            <td>
                                @if (item.OutCheckNumber != null)
                                {
                                    @Html.displayFor(modelItem => item.OutCheckNumber)
                                }
                                else
                                {
                                    <b>N/A</b>
                                }

                            </td>
                            <td>
                                @if (item.InvoiceNumber != null)
                                {
                                    @Html.displayFor(modelItem => item.InvoiceNumber)
                                }
                                else
                                {
                                    <b>N/A</b>
                                }

                            </td>
                            <td>
                                @if (item.PurchaSEOrderNumber != null)
                                {
                                    @Html.displayFor(modelItem => item.PurchaSEOrderNumber)
                                }
                                else
                                {
                                    <b>N/A</b>
                                }
                            </td>
                            <td>
                                @Html.displayFor(modelItem => item.LedgerAccount.Title)
                            </td>
                            <td>
                                @if (item.IsDebit == true)
                                {
                                    @Html.displayFor(modelItem => item.DebitAmount)
                                }
                                else
                                {
                                    <b>N/A</b>
                                }

                            </td>
                            <td>
                                @if (item.IsCredit == true)
                                {
                                    @Html.displayFor(modelItem => item.CreditAmount)
                                }
                                else
                                {
                                    <b>N/A</b>
                                }
                            </td>
                            <td>
                                @Html.displayFor(modelItem => item.TransactionDate)
                            </td>
                            <td>

                                @if (ViewBag.Edit == true)
                                {
                                    @Ajax.ModalDialogActionLink("Edit","Edit","btn btn-warning btn-sm",new { id = item.TransactionId })
                                }

                                @if (ViewBag.Read == true)
                                {
                                    @Ajax.ModalDialogActionLink("Details","Details","Transaction Details","btn btn-info btn-sm",new { id = item.TransactionId })
                                }

                                @if (ViewBag.Delete == true)
                                {
                                    @Ajax.ActionLink("Delete","Delete","Tranaction",new { id = item.TransactionId },new AjaxOptions()
                                             {
                                                 HttpMethod = "Delete",Confirm = "Are you sure you want to delete " + item.Description + "Transaction",},new { @class = "btn btn-danger btn-sm Delete" })
                                }
                            </td>
                            <td>
                            
                            </td>
                        </tr>

                        }
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

解决方法

我复制了你的错误。试试这个。

而不是这个:

@model List<BestenEquipment.Models.AccountingViewModels>

使用这个:

@model IEnumerable<BestenEquipment.Models.AccountingViewModels>

最后,删除 Items 循环中的 foreach 词,它应该是:

@foreach (var item in Model)
,
Public class AcctModel
{
public IEnumerable<AccountingViewModels> Items {get; set;}
}

在 view.cshtml 中

foreach(var item in Model.Items)
{
// Your code here
}
,

我发现当您只列出记录时,使用 SQL 视图会更容易。没有任何创建或编辑,因此只需填充您需要的内容就更容易了。数据库的工作就是做这项工作,所以为什么不让它呢!

这是我所做的,以防有人需要这样的东西,或者正在寻找一种更简洁的方法来做到这一点。 请记住,我需要从 2 个独立数据库中的表进行联接。在同一个数据库中创建视图更容易,您只需选择表,然后选择您想要的字段。

首先创建视图,在我的情况下,我需要使用别名进行查询并且没有使用 GUI。

SQL:

SELECT        t.TransactionId,t.Description,t.InCheckNumber,t.OutCheckNumber,t.InvoiceNumber,t.PurchaseOrderNumber,la.Title,t.DebitAmount,t.CreditAmount,t.TransactionDate,t.SavedDocument,t.CreatedDate,t.CreatedBy,tt.Type,cn.CompanyName,v.Name
FROM            dbo.LedgerAccount AS la INNER JOIN
                     dbo.[Transaction] AS t ON la.LedgerAccountId = t.LedgerAccountId 
INNER JOIN
                     dbo.TransactionType AS tt ON t.Type = tt.TypeId INNER JOIN
                     OtherDBName.dbo.CompanyNames AS cn ON t.CompanyId = 
cn.CompanyId LEFT OUTER JOIN
                     OtherDbName.dbo.Vendors AS v ON t.VendorId = v.VendorId

我将事务表 t 称为类型表 tt,当您引用另一个数据库时,您必须使用 dbname.schema.table.column 这些我给了名称 cn用于 CompanyNames 表,v 用于 Vendors 表。在我的特殊情况下,我不会总是在每条记录中都有供应商名称,因此您需要执行 LEFT OUTER JOIN
创建完成后,您现在可以返回到您的项目并创建实体。

在您的上下文中,您将创建它,就好像它只是另一个表一样。除了不映射它。没有必要。我们不会将其用于 CRUD 操作。 我调用了视图 TransactionsView:

public class AccountingEntities : DbContext
{
    public AccountingEntities() : base("AccountingConnection")
    {
    }

    [NotMapped]
    public IDbSet<TransactionsView> TransactionsView { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    }
}

用途:

using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.ComponentModel.DataAnnotations.Schema;

然后创建模型 TranactionsView

using System;
using System.ComponentModel.DataAnnotations;

namespace YourProject.AccountingDTO.Entities
{
public class TransactionsView
{
    [Key]
    public Guid TransactionId { get; set; }
    [Display(Name = "Desc")]
    public string Description { get; set; }
    [Display(Name = "Company")]
    public string CompanyName { get; set; }
    [Display(Name = "Vendor")]
    public String Name { get; set; }
    [Display(Name = "Rec Chk #")]
    public string InCheckNumber { get; set; }
    [Display(Name = "Sent Chk #")]
    public string OutCheckNumber { get; set; }
    [Display(Name = "Invoice #")]
    public string InvoiceNumber { get; set; }
    [Display(Name = "PO #")]
    public string PurchaseOrderNumber { get; set; }
    [Display(Name = "Ledger Acct")]
    public string Title { get; set; }
    [Display(Name = "Credit")]
    public decimal? DebitAmount { get; set; }
    [Display(Name = "Debit")]
    public decimal? CreditAmount { get; set; }
    [Display(Name = "Transaction")]
    [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}",ApplyFormatInEditMode = false)]
    public DateTime TransactionDate { get; set; }
    [Display(Name = "Doc Link")]
    public string SavedDocument { get; set; }
    [Display(Name = "Created")]
    [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}",ApplyFormatInEditMode = false)]
    public DateTime CreatedDate { get; set; }
    [Display(Name = "Created By")]
    public string CreatedBy { get; set; }
    [Display(Name = "Type")]
    public string Type { get; set; }
    }
}

控制器中的:

    private readonly AccountingEntities account = new AccountingEntities();
    // GET: Transaction
    public ActionResult Index()
    {
        return View(account.TransactionsView.ToList());
    }

在视图中,您只需创建一个列表视图并将您的 @model 放在顶部:

@model IEnumerable<YourProject.AccountingDTO.Entities.TransactionsView>

如果我遗漏了一些我可以回答您可能提出的任何问题的内容,我会尽量做到彻底。我一直将这些用于列表视图和表格

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。