错误的原因是什么" IModelBinder"以及如何解决?

时间:2018-02-15 21:56:23

标签: ajax asp.net-mvc model-binding imodelbinder

我正在编辑一个asp.net MVC项目。有一个javascript对API控制器进行ajax调用。我没有写这个ajax脚本,而且它工作得很好。我已经在数据项目中添加了一些模型(.cs文件),突然之间我收到了这个错误:

<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>
Could not create a 'IModelBinder' from 'DataSourceRequestModelBinder'. Please ensure it derives from 'IModelBinder' and has a public parameterless constructor.
</ExceptionMessage>
<ExceptionType>System.InvalidOperationException</ExceptionType>
<StackTrace>
at     System.Web.Http.ModelBinding.ModelBinderAttribute.GetModelBinder(HttpConfiguration configuration, Type modelType) at System.Web.Http.ModelBinding.ModelBinderAttribute.GetBinding(HttpParameterDescriptor parameter) at System.Web.Http.ModelBinding.DefaultActionValueBinder.GetParameterBinding(HttpParameterDescriptor parameter) at System.Array.ConvertAll[TInput,TOutput](TInput[] array, Converter`2 converter) at System.Web.Http.ModelBinding.DefaultActionValueBinder.GetBinding(HttpActionDescriptor actionDescriptor) at System.Web.Http.Controllers.HttpActionDescriptor.get_ActionBinding() at System.Web.Http.Controllers.ApiControllerActionSelector.ActionSelectorCacheItem..ctor(HttpControllerDescriptor controllerDescriptor) at System.Web.Http.Controllers.ApiControllerActionSelector.<>c__DisplayClass2.<GetInternalSelector>b__0(Object _) at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory) at System.Web.Http.Controllers.ApiControllerActionSelector.GetInternalSelector(HttpControllerDescriptor controllerDescriptor) at System.Web.Http.Controllers.ApiControllerActionSelector.SelectAction(HttpControllerContext controllerContext) at System.Web.Http.ApiController.ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken) at System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsyncInternal(HttpRequestMessage request, CancellationToken cancellationToken) at System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)

我不知道我为此做了什么并且无法在线发现此错误。我在StackOverflow上发现了有关IModelBinder的问题,我似乎正在做所有的事情(例如,WebAPI ModelBinder Error)。

导致此错误的原因是什么?如何修复?

这是ajax电话。

$.ajax({
        url: "/api/WorkOrderApi/GetNewAdminWorkOrder/" + vLocId + "?usr=" + vUsr + "&usrTyp=" + vUsrTyp,
        dataType: "json",
        type: "GET",
        success: function(model) {
            var viewModel = kendo.observable(model);

            kendo.bind(form, viewModel);
            var woAcct = $('#AcctId');
            woAcct.html(viewModel.AccountId);
         },
        error: function (XMLHttpRequest, textStatus, errorThrown)
        {
            alert("Status: " + textStatus); alert("Error: " + errorThrown);
        }

    });

这是控制器中的服务器端代码。如果我在这里设置一个断点,它就不会被击中:

        public ARMS.OpenAccess.WrkOrdTemp GetNewAdminWorkOrder(int id, int usr, int usrTyp)
    {

        var obj = new ARMS.OpenAccess.WrkOrdTemp
        {
            ProblemDescription = ""
           ,
            WorkOrderStatus = 1
           ,
            WorkOrderDate = DateTime.Today
           ,
            WorkOrderPriority = 7
        };

        int compToUse = 0;

        string companyNameToUse = "";

        int locToUse = 0;

        string locationNameToUse = "";

        string acctIdToUse = "";

        var locObj = new List<ClsDataUtil>();

        obj.Companies = rep.GetCustomersByUsrIdandType(usr, usrTyp, out compToUse, out acctIdToUse, out locToUse, out locObj);

        if (id > 0)
        {
            compToUse = rep.GetCompanyIdByLocationId(id);
            acctIdToUse = rep.GetAccountIdByCompanyId(compToUse);
            locObj = (List<ClsDataUtil>)rep.GetCoLocationByCompanyId(compToUse);
            locToUse = id;
        }
        else if (id == 0)
        {
            compToUse = obj.Companies.FirstOrDefault().Id;
            acctIdToUse = rep.GetAccountIdByCompanyId(compToUse);
            locObj = (List<ClsDataUtil>)rep.GetCoLocationByCompanyId(compToUse);
            locToUse = locObj.FirstOrDefault().Id;
        }

        companyNameToUse = rep.GetCompanyNameById(compToUse);
        locationNameToUse = rep.GetLocationNameByLocationID(locToUse);
        obj.CompanyName = companyNameToUse;
        obj.LocationName = locationNameToUse;

        obj.Locations = locObj;

        obj.WoTempId = rep.UpdateWoTempCompandLoc(0, compToUse, locToUse);

        obj.ReferenceNumber = GetLocPo(locToUse);

        obj.CompanyId = compToUse;

        obj.AccountId = acctIdToUse;

        obj.LocationId = locToUse;

        obj.Vendors = (obj.LocationId == null || obj.LocationId == 0) ? rep.GetLocVendors() : rep.GetLocVendorsByPostal(obj.LocationId, obj.ServiceType);


        if (obj.Vendors.Count > 0)
            obj.VendorId = obj.Vendors.Select(x => x.Id).Min();

        obj.LaborWorkCodes = rep.GetCodeWorkByCodeTypeId(10).OrderBy(x => x.Name);

        obj.ServiceTypes = rep.GetWoServiceTypes();

        rep.UpdateWoTempServiceType(obj.WoTempId, obj.ServiceType);

        obj.PriorityTypes = rep.GetCodePriorityByForType("WorkOrder");

        var StatusTypes1 = rep.GetWorkCodeStatusActiveByType("WorkOrder").Where(x => !x.Name.ToLower().Contains("complete")).OrderByDescending(o => o.Name);
        var StatusTypes2 = rep.GetWorkCodeStatusActiveByType("WorkOrder").Where(x => x.Name.ToLower().Contains("to be approved"));
        IQueryable<ClsDataUtil> StatusTypes = StatusTypes1;
        ClsDataUtil statusType2 = StatusTypes2.FirstOrDefault();
        List<ClsDataUtil> lstStatusTypes = StatusTypes.ToList();
        lstStatusTypes.Add(statusType2);
        obj.StatusTypes = lstStatusTypes.AsQueryable();

        obj.RateTypes = rep.GetCodeTypesById(17);

        obj.Techs = rep.GetLocResourceTechsByVendor(obj.VendorId);

        obj.UseLocContract = "No";

        if (rep.HasLocContract(locToUse))
        {

            obj.LstCustomerContract = rep.GetRWOCoLocationContractByLocId(locToUse);

            obj.UseLocContract = "Yes";

        }
        else
        {
            obj.LstCustomerContract = rep.GetRWOCustomerContractByCompId(compToUse);
        }

        var venId = rep.GetCompanyIdByLocationId(obj.VendorId);

        obj.LstVendorContract = rep.GetVendorContracts(venId, compToUse);

        return obj;

    } // GetNewAdminWorkOrder

这是从IModelBinder类派生的DataSourceRequestModelBinder.cs。我没有对此进行任何修改,因为它正在发挥作用。

using System;
using System.Collections.Generic;
using System.Web;
using System.Linq;
using System.Web.Http.Controllers;
using System.Web.Http.ModelBinding;
using Kendo.Mvc;
using Kendo.Mvc.Infrastructure;
using Kendo.Mvc.UI;

namespace ARMS.ModelBinders
{
public class DataSourceRequestModelBinder : IModelBinder
{
    public DataSourceRequestModelBinder()
    {

    }
    public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
    {
        DataSourceRequest request = new DataSourceRequest();

        string sort, group, filter, aggregates;
        int currentPage;
        int pageSize;

        if (TryGetValue(bindingContext, GridUrlParameters.Sort, out sort))
        {
            request.Sorts = GridDescriptorSerializer.Deserialize<SortDescriptor>(sort);
        }

        if (TryGetValue(bindingContext, GridUrlParameters.Page, out currentPage))
        {
            request.Page = currentPage;
        }

        if (TryGetValue(bindingContext, GridUrlParameters.PageSize, out pageSize))
        {
            request.PageSize = pageSize;
        }

        if (TryGetValue(bindingContext, GridUrlParameters.Filter, out filter))
        {
            request.Filters = FilterDescriptorFactory.Create(filter);
        }

        if (TryGetValue(bindingContext, GridUrlParameters.Group, out group))
        {
            request.Groups = GridDescriptorSerializer.Deserialize<GroupDescriptor>(group);
        }

        if (TryGetValue(bindingContext, GridUrlParameters.Aggregates, out aggregates))
        {
            request.Aggregates = GridDescriptorSerializer.Deserialize<AggregateDescriptor>(aggregates);
        }

        bindingContext.Model = request;
        return true;
    }

    private bool TryGetValue<T>(ModelBindingContext bindingContext, string key, out T result)
    {
        var value = bindingContext.ValueProvider.GetValue(key);

        if (value == null)
        {
            result = default(T);

            return false;
        }

        result = (T)value.ConvertTo(typeof(T));

        return true;
    }
}

}

0 个答案:

没有答案