向控制器发送多个复选框的异常?

时间:2017-10-23 19:43:33

标签: c# asp.net-mvc

我创建了一个多重复选框,但是当它发送到控制器时会抛出一个异常,我无法理解会发生什么。

我该如何解决这个问题?

模型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() { }
}

模型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() { }
}

控制器

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");

        }

查看

@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>

异常

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

1 个答案:

答案 0 :(得分:1)

异常消息“无法创建接口的实例”非常简单:模型绑定器无法在视图页面IPagedList<ContaPagarReceberModel>中定义IPagedList接口的空构造函数用于存储特定范围的List<T>集合的接口,永远不会为null或空ctor)。声明List的viewmodel集合,稍后将包含IPagedList

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() { }
}

然后,记得在控制器操作方法中将IPagedList分配给创建的视图模型列表(即List<ContaPagarReceberModel>):

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);
}

最重要的部分 - 将所有IPagedList接口属性替换为视图页面内的viewmodel属性列表(即将lista的所有索引器替换为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>

类似问题:

Cannot create an instance of an interface (PagedList)

MVC posting IPagedList

相关问题