Returning selected data to Razor in anonymous object

Asked

Viewed 434 times

0

I have a controller where I look for the birthday kids of the month. But I have more than 1000 birthday girls per month, returning a table with more than 50 attributes of each one, thus making the query time consuming.

    public ActionResult Aniversariantes()
    {
        var usuarios = usuarioRepository.Lista.Where(u => u.DtNascimento.Month == DateTime.Now.Month);
        var usuariosOrdenados = usuarios.OrderBy(u => u.DtNascimento.Day)ToList();
        return View(usuariosOrdenados);
    }

To try to solve, I tried to search only the fields I wish to show in my View.

public ActionResult Aniversariantes()
    {
        var usuarios = usuarioRepository.Lista.Where(u => u.DtNascimento.Month == DateTime.Now.Month);
        var usuariosOrdenados = usuarios.OrderBy(u => u.DtNascimento.Day).Select(x => new{x.DtNascimento, x.NmFuncionario, x.Descricao}).ToList();
        return View(usuariosOrdenados);
    }

But this way I get the following error when accessing the View:

The model item passed into the Dictionary is of type 'System.Collections.Generic.List1[<>f__AnonymousType23[System.Datetime,System.String,System.String]]', but this Dictionary requires a model item of type 'System.Collections.Generic.Ienumerable`1[Portalrh.DomainModel.Entities.Usuario]'.

Stack tracking

[InvalidOperationException: The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[<>f__AnonymousType2`3[System.DateTime,System.String,System.String]]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[PortalRH.DomainModel.Entities.Usuario]'.]
   System.Web.Mvc.ViewDataDictionary`1.SetModel(Object value) +378
   System.Web.Mvc.ViewDataDictionary.set_Model(Object value) +47
   System.Web.Mvc.ViewDataDictionary..ctor(ViewDataDictionary dictionary) +614
   System.Web.Mvc.ViewDataDictionary`1..ctor(ViewDataDictionary viewDataDictionary) +37
   System.Web.Mvc.WebViewPage`1.SetViewData(ViewDataDictionary viewData) +98
   System.Web.Mvc.WebViewPage.set_ViewData(ViewDataDictionary value) +39
   System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +425
   System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +382
   System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +431
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +39
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +116
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +529
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +106
   System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +321
   System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +185
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +42
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +40
   System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +34
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +44
   System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +39
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +62
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +39
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +39
   System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +39
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +40
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9715856
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

View

@model IEnumerable<PortalRH.DomainModel.Entities.Usuario>


@{
    ViewBag.Title = "Aniversariantes do Mês";
}




<script type="text/javascript">
    var $j = jQuery.noConflict();
    $j(function() {
        $j("#myTable").kendoGrid({
            sortable: true,
            pageable: true,
            dataSource: { pageSize: 15 }
        });
    });
</script>

<div class="Nome">
    <p><strong><font face="Arial" size="2"> @ViewBag.Matricula / @ViewBag.Contrato - @ViewBag.Nome</font></strong></p>
</div>
<div class="mapLocal">
    <img src="~/Content/img/sitemap.ico" width="19" height="19" /> Você está em: <i>@ViewBag.Title</i>
</div>
<br />
<div class="row">
    <div class="col-md-2">

    </div>
    <div class="col-md-8">
        <div class="panel panel-default">
            <div class="panel-heading">
                <h5><strong>Aniversariantes do Mês</strong></h5>
            </div>
            <table id="myTable">
                <thead>
                    <tr>
                        <th>Nome do Funcionário</th>
                        <th>Secretaria</th>
                        <th>Data do Aniversário</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach (var item in Model)
                    {
                        <tr>
                            <td>
                                @item.NmFuncionario
                            </td>
                            <td>
                                @item.Descricao
                            </td>
                            <td>
                                @item.DtNascimento.Day.ToString("00")/ @item.DtNascimento.Month.ToString("00")
                            </td>
                        </tr>
                    }
                </tbody>
            </table>

        </div>
    </div>
</div>

Doubt: How to return only the three fields I really need in the query?

Remembering that the way I am doing, when debugging the code I get the correct result, only the three fields. But when listing in View I get this error.

1 answer

0


Two forms:

The recommended form

Create a ViewModel typed with the 3 fields you need. Pass to Razor a typed collection:

@model IEnumerable<PortalRH.DomainModel.ViewModels.UsuarioViewModel>

The way not recommended

It works, but it tends to create chaos. Make Razor accept a dynamic object:

@model IEnumerable<dynamic>

It is not recommended because all fields are solved at runtime, which makes it difficult to prevent errors.

  • By creating the Viewmodel i need to make some changes to my Controller?

  • In the first form, Select would look like this: .Select(x => new UsuarioViewModel {x.DtNascimento, x.NmFuncionario, x.Descricao}.

  • Thank you very much, solved my problem. : .Select(x => new User viewmodel() { Description = x.Description, Nmfuncionaio = x.Nmfuncionaio, Dtnascimento = x.Dtnascimento }). Tolist();

  • @Renilsonandrade Exactly that.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.