Sequence contains error in Elements Asp.net

Asked

Viewed 1,434 times

0

Good morning.

I am trying to send an ajax request in jquery, but it returns this error. Sequence contains in Elements, I’m wanting to present data in bootgrid

public ParametrosPaginacao(NameValueCollection dados)
        {

            string chave = dados.AllKeys.Where(k => k.StartsWith("asc")).First();

            string ordenacao = dados[chave];
            string campo = chave.Replace("sort[", String.Empty).Replace("]", String.Empty);

            CampoOrdenado = String.Format("{0} {1}", campo, ordenacao);

            Current = int.Parse(dados["current"]);
            RowCount = int.Parse(dados["RowCount"]);
            SearchPhrase = dados["searchPhrase"];

        }

        public int Current { get; set; }
        public int RowCount { get; set; }
        public string SearchPhrase { get; set; }
        public string CampoOrdenado { get; set; }

}

My ajax

$(document).on('click', '#contratos_vigentes', function () {

    var Status = $('#Status option:selected').text();
    var Gestor_Acc = $('#Gestor_Acc option:selected').text();
    var Gestor_Retida = $('#Gestor_Retida option:selected').text();
    $.ajax({
        url: 'FiltrarEPaginar',
        type: 'post',
        dataType: 'json',
        data: { status : Status, gestor_acc : Gestor_Acc, gestor_Retida : Gestor_Retida },

    });
    //window.location.href = "Contratos_Vigentes?status=" + Status + "&gestor_acc=" + Gestor_Acc + "&gestor_retida=" + Gestor_Retida;

});

My controller

public JsonResult Contratos_Vigentes(ParametrosPaginacao parametrosPaginacao, string status, string gestor_acc, string gestor_retida)
        {
            DadosFiltrados dadosFiltrados = FiltrarEPaginar(parametrosPaginacao,  status, gestor_acc,  gestor_retida);

            return Json(dadosFiltrados, JsonRequestBehavior.AllowGet);
        }

        public DadosFiltrados FiltrarEPaginar(ParametrosPaginacao parametrosPaginacao, string status, string gestor_acc, string gestor_retida)
        {

            var areaVigentes = db.Contratos.Count();
            int total = 0;
            string[] usuario_perfil = User_Role();
            ViewBag.status = status;
            ViewBag.gestor_acc = gestor_acc;
            ViewBag.gestor_retida = gestor_retida;
            List<Contrato> contrato_saldo_Vigencia1 = new List<Contrato>();

            if (usuario_perfil[1] == "Administrador" || usuario_perfil[1] == "Accenture")
            {
                //Efetua busca com base nos filtros inseridos pelo usuário e retorna quantitativo de contratos com status Vigente
                contrato_saldo_Vigencia1 = db.Contratos.Where(a => a.DescStatusVigente == "Vigente").ToList();
            }
            else if (usuario_perfil[1] == "Accenture_Saldo_Vigencia")
            {
                contrato_saldo_Vigencia1 = db.Contratos.Where(a => a.DescStatusVigente == "Vigente" && a.EmailGestor == usuario_perfil[0]).ToList();
            }

            if (status != "" && status != null)
            {
                contrato_saldo_Vigencia1 = contrato_saldo_Vigencia1.Where(j => j.DescAreaCliente.Contains(status)).ToList();
            }
            if (gestor_acc != "" && gestor_acc != null)
            {
                contrato_saldo_Vigencia1 = contrato_saldo_Vigencia1.Where(j => j.DescGestorAcc == gestor_acc).ToList();
            }
            if (gestor_retida != "" && gestor_retida != null)
            {
                contrato_saldo_Vigencia1 = contrato_saldo_Vigencia1.Where(j => j.DescGestorRetida == gestor_retida).ToList();
            }
            var AreasAccenturePaginados = contrato_saldo_Vigencia1.OrderBy(parametrosPaginacao.CampoOrdenado).Skip((parametrosPaginacao.Current - 1) * parametrosPaginacao.RowCount).Take(parametrosPaginacao.RowCount);

            DadosFiltrados dadosFiltrados = new DadosFiltrados(parametrosPaginacao)
            {
                rows = AreasAccenturePaginados.ToList(),
                total = total
            };


            return dadosFiltrados;


        }

Stacktrace

[InvalidOperationException: Sequence contains no elements]
   System.Linq.Enumerable.First(IEnumerable`1 source) +403
   PortalAdmCC.ViewModels.ParametrosPaginacao..ctor(NameValueCollection dados) in C:\Users\gabriel.da.c.falieri\Documents\Visual Studio 2017\Projects\PACO\PortalAdmCC\PortalAdmCC\ViewModels\ParametrosPaginacao.cs:14
   PortalAdmCC.Infra.ParametrosPaginacaoModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) in C:\Users\gabriel.da.c.falieri\Documents\Visual Studio 2017\Projects\PACO\PortalAdmCC\PortalAdmCC\Infra\ParametrosPaginacaoModelBinder.cs:16
   System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +331
   System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +105
   System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__19(AsyncCallback asyncCallback, Object asyncState) +743
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +14
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
   System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +343
   System.Web.Mvc.Controller.<BeginExecuteCore>b__1c(AsyncCallback asyncCallback, Object asyncState, ExecuteCoreState innerState) +25
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +30
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
   System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +465
   System.Web.Mvc.Controller.<BeginExecute>b__14(AsyncCallback asyncCallback, Object callbackState, Controller controller) +18
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +20
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
   System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +374
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +16
   System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__4(AsyncCallback asyncCallback, Object asyncState, ProcessRequestState innerState) +52
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +30
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +384
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +48
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +443
   System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +132
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +163
  • Could include error stacktrace?

  • Sure@lgomide, I put stacktrace

  • If you could take a look please

  • Check the add-on I put (edited the answer)

  • Yes, but it turns out that I realized something today, this error is not happening only with this screen, even with others that were already ready

1 answer

1

The error says that you tried to extract an element from a sequence, but it had none. Probably the error comes from this line (method First() )

string chave = dados.AllKeys.Where(k => k.StartsWith("asc")).First();

Therefore, your code needs to address the case where there are no keys starting with "asc".

Your ajax code does not send the parameter parametrosPaginacao, which should be an object, for the controller. That’s why the ASP.NET MVC framework fails to execute the constructor. There are two options:

1 - Modify the constructor to handle the case where the parameter dice is null or void.

2 - Modify javascript to mount and send the Parametrospagination object to the controller.

  • Yes, the error comes from that line itself

  • <tr> <th data-column-id="Id" data-order="asc">Contract</th> <th data-column-id="Supplier">Supplier</th> <th data-column-id="Dtcreation">Start date</th> <th data-column-id="Dtfim">End Date</th> <th data-column-id="Gestor_acc">Acc</th> <th data-Formatter="Details" data-sortable="false">Details</th> </tr>

Browser other questions tagged

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