在一个视图中混合实体模型和视图模型

时间:2017-12-01 20:19:51

标签: c# asp.net-mvc asp.net-core-2.0

正如我开始明白的那样,在MVC中,所有关于视图模型都在视图中显示数据。但是当我的家庭控制器中的Index-method看起来像这样时;

<div class="form-group">
    <select class="form-control" name="anio"(change)="onChange($event.target.value)">
      <option *ngFor="let list of listaAnios" [ngValue]="list">{{list}}</option>
    </select>
</div>
<div class="form-group">
  <label class="col-sm-3 control-label" for="allMonths">Ver todos los meses:</label>
  <div class="col-sm-4">
    <input type="checkbox" name="allMonths" id="allMonths" [ngModel]="" (ngModelChange)="showAll($event)">
  </div>
</div>
<div class="clearfix"></div>
<div *ngIf="!estados">
  Cargando Listado de Pagos...
</div>
<div *ngIf="estados" class="table-responsive col-lg-12 tablilla">
  <div>
    <ay-treeTable [value]="datos.data">
      <ay-column field="nom_item" header="Ingresos y Gastos"></ay-column>
      <ng-container *ngFor="let month of finalarr | slice: this.listaMonthsNames.length - this.check">
        <ay-column field="{{month[0]}}" header="{{month[1]}}"> {{month[0]}} </ay-column>
      </ng-container>

    </ay-treeTable>
  </div>
</div>

如何在我的网页中插入带有viewmodel的局部视图,如下所示(_Layout.cshtml):

public async Task<IActionResult> Index()
{
    return View(await _context.Products.ToListAsync());
}

毕竟,index-method需要一个实体模型。如果我尝试将viewmodel传递给索引视图,我会得到一个异常,告诉我在_context中找不到该模型。

2 个答案:

答案 0 :(得分:1)

您可能已经知道为什么ViewModel应该在您的视图中使用,为什么不在实体中使用,但如果您不这样做,那么让我解释一下。

当您在页面上显示数据时,通常需要ItemSelectedHideItem等属性,即仅与页面相关的任何内容,entities上不需要

现在我们知道为什么需要保留entitiesviewmodels的重要性。现在的问题是如何转移数据

from entities to viewmodels when displaying data

OR

from viewmodels to entities when updating data on db

您有两个选择

  • 编写自己的映射逻辑进行转换。
  • 使用自动映射器(http://automapper.org/)为您完成工作,而且只需要您的努力。

如果您正在考虑使用AutoMapper,那么还要查看专门针对Entity Framework的https://github.com/AutoMapper/AutoMapper.EF6

答案 1 :(得分:0)

你可以使用这里的子动作方法

@JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id")
public class User {

正如你可以看到这个索引页面剂量已经分配给它的任何模型现在检查Homesection动作看起来像这样

 @{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_LayoutHome.cshtml";
}

@Html.Action("HomeSection")

@Html.Action("AboutSection") 

和_HomeSectionPartial视图看起来像这样

  [ChildActionOnly]
        public async Task<ActionResult> HomeSection()
        {
            try
            {
                Home home = new Home();
                home = await HomePageBLL.GetHomeSection();
                return View("_HomeSectionPartial", home);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

当您想要使用不同模型的不同局部视图在同一主视图中呈现时,这是一个最佳的想法,即使主视图也可以有模型库

相关问题