8

I am trying to write a auto-complete with ajax in MVC5 but no matter what I try I get the error invalid JSON primitive. When I enter the url manually localhost:5088/GetData?inpt=[query] I am able to see the return json.

From what I understand online , I am giving the "data:" parameter wrong. I tried putting them in "" but it didn't work.

My Controller :

  public  JsonResult GetData(string inpt)
        {
            try
            {
                var node = //some values here , cause its too long I deleted it 
                foreach (var node in q)
                {
                    string scity = node.Attribute("CityName").Value.ToUpper(new CultureInfo("tr-TR", false));
                    string ccity = node.Attribute("CityCode").Value;
                    string ccode = node.Attribute("CountryCode").Value;
                    if (ccity != oldcity)
                    {
                        result.Add(new HavaAlani { SehirAdi = scity, HavaAlaniKodu = ccity, HavaAlaniAdi = scity + ", " + ccode, Sehirmi = true });
                        oldcity = ccity;
                    }
                    result.Add(new HavaAlani { SehirAdi = scity, HavaAlaniKodu = node.Attribute("Code").Value, HavaAlaniAdi = node.Value, Sehirmi = false });
                }
            }
            catch
            {

            }

            return Json(result, JsonRequestBehavior.AllowGet);
        }
    }

My JS :

    $('input.suggestBox').each(function () {
    //$(this).jsonSuggest(air.Lines);
    $(this).autocomplete({
        source: function (request, response) {
            $.ajax({
                url: "dataAl/GetData",
                data: { inpt: request.term },
                dataType: "json",
                type: "POST",
                contentType: "application/json; charset=utf-8",
                dataFilter: function (data) { return data; },
                success: function (data) {
                    response($.map(data.d, function (item) {
                        return {
                            code: item.HavaAlaniKodu,
                            value: item.HavaAlaniAdi,
                            iscity: item.Sehirmi
                        }
                    }))
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert(XMLHttpRequest.responseText);
                }
            });
        },
        minLength: 2
    }).data("ui-autocomplete")._renderItem = function (ul, item) {
        var cls = "airport";
        if (item.iscity)
            cls = "city";
        return $("<li></li>")
                .data("item.autocomplete", item)
                .append("<span class='span-" + cls + "'></span>")
                .append("<a class='ui-autocomplete-" + cls + "'>" + item.value + " (" + item.code + ")" + "</a>")
                .appendTo(ul);
    };

});
4
  • 1
    Can you post an example of the JSON Returned? Mar 12, 2014 at 18:51
  • It doesnt return JSOn , it gives warning "invalid JSOn primitive:inpt." But it gives the error in html format within title tag of head
    – Burak Gazi
    Mar 12, 2014 at 19:11
  • 1
    hmm... That is strange, I though that particular error originated with jquery, not MVC. If you put a break point in that action does it appear to complete? If not can you also show where result is declared. Also try changing DataType to "text json" or "text/json" Mar 12, 2014 at 19:34
  • Added to answer - I believe you need to stringify your data object as well. Mar 12, 2014 at 19:55

1 Answer 1

21

Comment was getting a bit long so adding this as an answer-

The first thing to try would be modifying your content type per this post: MVC JSON method returning invalid JSON to JQuery?

Try "application/json".

also wrap your data object in

  JSON.stringify()

If that doesn't work can you tell me where result is coming from in your action - I'm not seeing the declaration. Also add a break point and ensure that you can step into that method.

2
  • After setting a breakpoint in System.Web.MVC.JSONValueProviderFactory, I found that my 'application/json' POST data had been url-encoded by jQuery/ajax. To prevent this, add the option processData: false to your request and take @Kelly Gendron's advice and call stringify on your object as well. MVC looks for the 'application/json' option and expects it to be a regular json string that it then deserializes. May 27, 2016 at 16:40
  • 1
    example: $.ajax({ type : 'POST', contentType : "application/json; charset=utf-8", url : 'equipment/GetData', data : JSON.stringify({ "start" : $("#startTime").val(), "end" : $("#endTime").val(), "name" : "name" }), processData : false, dataType : 'application/json' }) May 27, 2016 at 16:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.