weixin_33695082 2016-01-28 15:30 采纳率: 0%
浏览 45

AJAX通话为空

I have an AJAX call in the View, and its having difficulties pulling from DB to the populate the drop down list. The DB has been populated. Inside the browser console I can see it has found the correct ID, but I receive the following error:

"Failed to load resource: the server responded with a status of 500 (Internal Server Error)"

Clicking this link take me to a server error:

"The parameters dictionary contains a null entry for parameter 'serviceId' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.JsonResult GetServiceDetails(Int32)' in 'YardLad.Controllers.ServiceController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. Parameter name: parameters"

Here is the code I have so far:

AJAX Call:

function GetServices() {
        $.ajax({
            type: "GET",
            url: "/Service/GetServices",
            data: { serviceAreaId: $('#ServiceAreaId').val() },
            datatype: 'JSONP',
            async: true
        })
        .done(function (services) {
            $('#ServiceId').empty(); //commenting this line gets the field to never populate with nulls, leaving the 
                                     //"loading services..." there permanently, also brings up the request a contractor button.
            $.each(services, function (i, service) { //the i is the index being passed to it... service is the value
                $("#ServiceId").append(
                    $('<option/>')
                    .attr('value', this.ServiceId)
                    .text(this.Name)
                );
            });

            GetServiceDescription();
        });
    }

Controller:

//
    // GET: Service/GetServices/

    public JsonResult GetServices(int serviceAreaId)
    {
        // selected service area
        var selectedServiceArea = db.ServiceAreas.Where(sa => sa.ServiceAreaId == serviceAreaId).SingleOrDefault();
        var currentDate = DateTime.Now.AddHours(2);

        // list of contractors that are listed (and not expired) and have at least one contractor service added
        var contractors = db.Contractors.Where(c => c.IsActive == true).Where(c => c.ExpiresOn.Value >= currentDate).Where(c => c.ContractorServices.Count >= 1).ToList();
        HashSet<int> contractorIds = new HashSet<int>(contractors.Select(x => x.ContractorId));

        // filter list of contractors to include only those who offer services in the selected service area
        var primary = db.Contractors.ToList().FindAll(x => contractorIds.Contains(x.ContractorId))
            .Where(c => c.ServiceAreaId == serviceAreaId).Distinct().ToList();

        var secondary = db.ContractorServiceAreas.ToList().FindAll(x => contractorIds.Contains(x.ContractorId))
            .Where(csa => csa.ServiceAreaId == serviceAreaId).Select(x => x.Contractor).Distinct().ToList();

        foreach (var contractor in secondary)
        {
            if (primary.Contains(contractor) == false)
            {
                primary.Add(contractor);
            }
        }

        // only return services in the selected service area that contractors have added
        HashSet<int> filteredContractorIds = new HashSet<int>(primary.Select(x => x.ContractorId));

        var services = db.ContractorServices.ToList().FindAll(x => filteredContractorIds.Contains(x.ContractorId))
            .Select(x => x.Service).Distinct().OrderBy(s => s.ServiceCategory.Name).ThenBy(s => s.Name)
            .Select(x => new {
                ServiceId = x.ServiceId,
                Name = x.Name
            });

        return this.Json(services, JsonRequestBehavior.AllowGet);
    }

    //
    // GET: Service/GetServiceDetails/1

    public JsonResult GetServiceDetails(int serviceId)
    {
        var details = db.Services.Where(s => s.ServiceId == serviceId)
            .Select(x => new
            {
                Description = x.Description,
                BasePrice = x.BasePrice
            });

        return this.Json(details, JsonRequestBehavior.AllowGet);
    }

.cshtml

@using (Html.BeginForm("RequestService", "Service", FormMethod.Post))
{
<div class="two-third" style="margin-right: 0;">
    <div id="requestService" style="overflow: auto">
        <h2>Request a Service</h2>
        @Html.ValidationSummary(true)

        <div class="display-label">Select a State</div>
        <div class="editor-field">
            <select id="StateId" name="StateId">
                <option value="0">loading states...</option>
            </select>
        </div>

        <div class="display-label">Select a Service Area</div>
        <div class="editor-field">
            <select id="ServiceAreaId" name="ServiceAreaId">
                <option value="0">loading service areas...</option>
            </select>
        </div>

        <div class="display-label">Select a Service</div>
        <div class="editor-field">
            <select id="ServiceId" name="ServiceId">
                <option value="0">loading services...</option>
            </select>
        </div>

        <div class="selectedService" style="display: none;">
            <div class="display-label">Service Description</div>
            <div class="editor-field" id="ServiceDescription"></div>
            <div class="serviceOptions" id="ServiceOptions"></div>
            <div style="text-align: right;">
                <input type="submit" id="SubmitRequest" value="Select a Contractor" />
            </div>
        </div>
    </div>
</div>

<div class="one-third" style="float: right; margin-top: 0;">
    <div id="summary">
        <h3>Yard Lad Service Estimate</h3>
        <p>This is an initial Yard Lad estimate. The end total may be higher or lower based upon the contractor you choose, 
        as well as the contractors on-site assessment. Payment adjustments are easy to make on site or online after the 
        service has been completed.</p>
        <div style="font-weight: bold;">Subtotal: $<span class="subtotal">0.00</span></div>
    </div>
</div>

<input type="hidden" class="stateId" name="StateId" value="0" />
<input type="hidden" class="serviceAreaId" name="ServiceAreaId" value="0" />
<input type="hidden" class="serviceId" name="ServiceId" value="0" />

After changing the Ajax call "url" The server error has slightly changed. I provided a picture of the update below: Server Error Image

  • 写回答

1条回答 默认 最新

  • weixin_33690963 2016-01-28 15:43
    关注

    When your server receives the HTTP Get request, it is expecting an Id in the query string inside of the url(ex Service/GetServices/1), which in in request header. Your Id is actually in the request body not in url. That is why your server code is complaining. To make this work, you can change your JavaScript code to

    function GetServices() {
            $.ajax({
                type: "GET",
                url: "/Service/GetServices/?serviceId=" + $('#ServiceAreaId').val(), 
                dataType: "jsonp",    
                async: true
            })
            .done(function (services) {
                $('#ServiceId').empty(); //commenting this line gets the field to never populate with nulls, leaving the 
                                     //"loading services..." there permanently, also brings up the request a contractor button.
                $.each(services, function (i, service) { //the i is the index being passed to it... service is the value
                $("#ServiceId").append(
                    $('<option/>')
                    .attr('value', this.ServiceId)
                    .text(this.Name)
                );
            });
    
            GetServiceDescription();
        });
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 u盘问题:盘符不显示 无媒体
  • ¥50 R语言读取nc按月均值转为tif
  • ¥30 智能车串级pid调参
  • ¥15 visual studio code翻译老是错误
  • ¥20 卫星测高数据的高程转换
  • ¥15 爬取招聘网站数据信息
  • ¥15 安装完tensorflow,import tensorflow as tf后报错,如何解决?
  • ¥15 ultralytics库导出onnx模型,模型失去预测能力
  • ¥15 linux下点对点协议连接2个USB串口的硬件流量控制问题
  • ¥15 SQL数据自动生成问题