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 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 matlab有关常微分方程的问题求解决
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法