0

I'm created a multiple checkbox but when send it to controller it throws an exception and I can't understand what happens.

How could I fix this ?

Model 1

public class ContaPagarReceberModel {

    [DisplayFormat(DataFormatString = "{0:000}", ApplyFormatInEditMode = true)]
    public long id                                      { get; set; }

    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
    public DateTime dtLancamento                        { get; set; }

    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
    public DateTime dtVencimento                        { get; set; }

    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
    public DateTime dtPagamento                         { get; set; }
    public String historico                             { get; set; }

    [DisplayFormat(DataFormatString = "{0:N}", ApplyFormatInEditMode = true)]
    public decimal valor                                { get; set; }
    public String tipoConta                             { get; set; }

    //usuario
    public String nomeUsuario                           { get; set; }
    public String emailUsuario                          { get; set; }
    public String refUsuario                            { get; set; }
    //

    public String refTransact                           { get; set; }

    public Boolean isBaixar                             { get; set; }

    public ContaPagarReceberModel() { }
}

Model 2

public class SearchContaPagarReceberModel{
    public IPagedList<ContaPagarReceberModel> lista                 { get; set; }
    public DateTime? dtIni                                           { get; set; }
    public DateTime? dtFim                                           { get; set; }
    public decimal total                                            { get; set; }

    public SearchContaPagarReceberModel() { }
}

Controller

public ViewResult viewAllPagar(int? page, DateTime? dtIni, DateTime? dtFim){
            IList<ContaPagarReceber> _lista = new ContaPagarReceberDAO().findAllPagarByStatus(0); //todas pagar ativa
            IList<ContaPagarReceberModel> _listaModel = new List<ContaPagarReceberModel>();

            SearchContaPagarReceberModel model = new SearchContaPagarReceberModel();
            try{
                int pagina = page ?? 1;
                if (_lista.Count > 0){
                    foreach (ContaPagarReceber cpr in _lista){
                        ContaPagarReceberModel cprm = new ContaPagarReceberModel();
                        cprm.id = cpr.id;
                        cprm.dtLancamento = cpr.dtLancamento;
                        cprm.dtVencimento = cpr.dtVencimento;
                        cprm.historico = cpr.historico;
                        cprm.valor = cpr.valor;
                        cprm.tipoConta = cpr.tipoConta == 1 ? "RECEBER" : "PAGAR";
                        cprm.emailUsuario = cpr.usuario.email;
                        cprm.nomeUsuario = cpr.usuario.nome;
                        cprm.refUsuario = cpr.refUsuario;
                        cprm.refTransact = cpr.referencia;
                        cprm.isBaixar = false;

                        _listaModel.Add(cprm);
                    }
                    model.lista = _listaModel.ToPagedList(pagina, 50);
                }

            }catch(Exception e){
                Debug.WriteLine("Erro viewAllPagar ContasPagRecController" + e.Message);
            }

            return View(model);
        }


//baixar contas
        public void baixaContasPagar(SearchContaPagarReceberModel model){
            Debug.WriteLine("Entreiii");

        }

View

@model SearchContaPagarReceberModel
@using PagedList.Mvc

@{
    ViewBag.Title = "viewAllPagar";
    Layout = "~/Views/Shared/_LayoutAdministracao.cshtml";
}

<div class="panel panel-red center-block">
    <div class="panel-heading bg-red clearfix">
        <strong>Contas a pagar</strong>
    </div>
    <div class="panel-body">
        <div class="alert alert-danger" id="errorMessage" style="display:none;">Alerta</div>

        @using (Html.BeginForm("baixaContasPagar", "ContasPagRec", FormMethod.Post, new { id = "baixaContasPagar" })){
            <table class="table table-bordered table-responsive table-striped table-hover" id="tableView">
                <thead class="CabecalhoTabela">
                    <tr>
                        <th>#ID</th>
                        <th>Lançamento</th>
                        <th>Vencimento</th>
                        <th>Histórico</th>
                        <th>Valor USD$</th>
                        <th>Conta</th>
                        <th>Favorecido</th>
                        <th>Email</th>  
                        <th>Função</th>                  
                        <th>Baixar<input type="checkbox" id="selectAll" class="form-control input-sm"></th>
                    </tr>
                </thead>
                <tbody class="conteudoTabela">               
                        @for (int i = 0; i < Model.lista.Count; i++ ){
                            <tr>
                                <td class="text-right">
                                                       @Model.lista[i].id
                                                       @Html.HiddenFor(x => x.lista[i].id)
                                </td>
                                <td class="text-center">@Model.lista[i].dtLancamento</td>
                                <td class="text-center">@Model.lista[i].dtVencimento</td>
                                <td class="text-center">@Model.lista[i].historico</td>                        
                                <td class="text-right">@Model.lista[i].valor</td>
                                <td class="text-center">@Model.lista[i].tipoConta</td>  
                                <td>@Model.lista[i].nomeUsuario</td>  
                                <td class="text-lowercase">@Model.lista[i].emailUsuario</td>
                                <td>@Model.lista[i].refUsuario)</td>
                                <td class="text-center">@Html.CheckBoxFor(x => x.lista[i].isBaixar, new { Class = "form-control input-sm checkBox" })</td>                               
                            </tr>
                        }                    
                </tbody>
            </table>

            <div class="pull-right">
                <input type="submit" value="Baixar Contas" class="btn btn-success btn-lg" />
            </div>
        }<!--/form-->

    </div>
    <div class="panel-footer clearfix">       
        Pagina @Model.lista.PageNumber de @Model.lista.PageCount
        @Html.PagedListPager(Model.lista, page => Url.Action("viewAllPropostasNegociadas", new { page = page, dtIni = Model.dtIni, dtFim = Model.dtFim }))
    </div>
</div>

Exception

Server Error in '/' Application.

Cannot create an instance of an interface.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.MissingMethodException: Cannot create an instance of an interface.

Source Error: 

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace: 


[MissingMethodException: Cannot create an instance of an interface.]
   System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0
   System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +113
   System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +232
   System.Activator.CreateInstance(Type type, Boolean nonPublic) +83
   System.Activator.CreateInstance(Type type) +6
   System.Web.Mvc.DefaultModelBinder.CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) +460
   System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +1137
   System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +628
   System.Web.Mvc.DefaultModelBinder.GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder) +59
   System.Web.Mvc.DefaultModelBinder.BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor) +653
   System.Web.Mvc.DefaultModelBinder.BindProperties(ControllerContext controllerContext, ModelBindingContext bindingContext) +180
   System.Web.Mvc.DefaultModelBinder.BindComplexElementalModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Object model) +106
   System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +2541
   System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +628
   System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +497
   System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +199
   System.Web.Mvc.Async.<>c__DisplayClass1e.<BeginInvokeAction>b__16(AsyncCallback asyncCallback, Object asyncState) +1680
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +59
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +151
   System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag, Int32 timeout) +94
   System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +540
   System.Web.Mvc.Controller.<BeginExecuteCore>b__1c(AsyncCallback asyncCallback, Object asyncState, ExecuteCoreState innerState) +82
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +73
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +151
   System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object callbackState, BeginInvokeDelegate`1 beginDelegate, EndInvokeVoidDelegate`1 endDelegate, TState invokeState, Object tag, Int32 timeout, SynchronizationContext callbackSyncContext) +105
   System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +595
   System.Web.Mvc.Controller.<BeginExecute>b__14(AsyncCallback asyncCallback, Object callbackState, Controller controller) +47
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +65
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +151
   System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object callbackState, BeginInvokeDelegate`1 beginDelegate, EndInvokeVoidDelegate`1 endDelegate, TState invokeState, Object tag, Int32 timeout, SynchronizationContext callbackSyncContext) +139
   System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +604
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +50
   System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__3(AsyncCallback asyncCallback, Object asyncState, ProcessRequestState innerState) +98
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +73
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +151
   System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object callbackState, BeginInvokeDelegate`1 beginDelegate, EndInvokeVoidDelegate`1 endDelegate, TState invokeState, Object tag, Int32 timeout, SynchronizationContext callbackSyncContext) +106
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +551
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +88
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +50
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +301
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
FernandoPaiva
  • 4,410
  • 13
  • 59
  • 118

1 Answers1

1

The exception message "Cannot create instance of an interface" is pretty straightforward: the model binder can't define empty constructor of IPagedList<ContaPagarReceberModel> interface in view page (IPagedList interface designed to store specific range of List<T> collection, never have null or empty ctor). Declare a List of viewmodel collection which will contains IPagedList later:

public class SearchContaPagarReceberModel {
    public IPagedList<ContaPagarReceberModel> lista { get; set; }

    // this property will be passed to view instead of 'lista' above
    public List<ContaPagarReceberModel> ContaPagarReceberModels { get; set; }

    // other properties

    public SearchContaPagarReceberModel() { }
}

Then, remember to assign IPagedList to created viewmodel list (i.e. List<ContaPagarReceberModel>) inside controller action method:

public ViewResult viewAllPagar(int? page, DateTime? dtIni, DateTime? dtFim)
{
     // other stuff

     SearchContaPagarReceberModel model = new SearchContaPagarReceberModel();
     try 
     {
            // other stuff

            // assign IPagedList interface property
            model.lista = _listaModel.ToPagedList(pagina, 50);

            // add the IPagedList content to viewmodel list
            model.ContaPagarReceberModels = model.lista.ToList();

            // other stuff
     } 
     catch (Exception e)
     {
         Debug.WriteLine("Erro viewAllPagar ContasPagRecController" + e.Message);
     }

     return View(model);
}

And the most important part - replace all IPagedList interface properties to the list of viewmodel properties inside view page (i.e. replace all indexers of lista to ContaPagarReceberModels):

<tbody class="conteudoTabela">               
     @for (int i = 0; i < Model.ContaPagarReceberModels.Count; i++)
     {
         <tr>
            <td class="text-right">
                @Model.ContaPagarReceberModels[i].id
                @Html.HiddenFor(x => x.ContaPagarReceberModels[i].id)
            </td>
            <td class="text-center">@Model.ContaPagarReceberModels[i].dtLancamento</td>
            <td class="text-center">@Model.ContaPagarReceberModels[i].dtVencimento</td>
            <!-- other stuff -->               
        </tr>
    }                    
</tbody>

Similar issues:

Cannot create an instance of an interface (PagedList)

MVC posting IPagedList

Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61