1

What I am doing is, i am getting data from server side using mvc. The data is properly coming in return part. But when I m debugging in the client side, I am only getting the parameter value as [.

Below is the JSON response which I am getting.

[{"VENDORNAME":"ABC","VENDORCODE":"1234"},{"VENDORNAME":"Abc test","VENDORCODE":"233311"},{"VENDORNAME":"ABC 2","VENDORCODE":"12345"}]

But when I check in the client I get it only [ in the parameter.

Below is that code

getValue: function (element) {        
        return {
            label: element.VENDORNAME,
            value: element.VENDORCODE
         };
    },  

in element i only get as [

Please suggest where I am wrong

update

Here is the full code

var autocompleteOptions = {        

    url: function (phrase) {
        return AppConfig.PrefixURL + 'App/GetVendorData';
    },

    getValue: function () {        
        return {
            label: element.VENDORNAME,
            value: element.VENDORCODE
         };
    },      

    ajaxSettings: {
        dataType: "json",
        method: "POST",
        data: {
            dataType: "json",                
        }
    },        

    preparePostData: function (data) {
        data.phrase = $("#txtAssignVendor").val();           
        return data;
    },

    requestDelay: 400
};

And reference link below

http://easyautocomplete.com/examples#examples-ddg

Server code

[HttpPost]
    public JsonResult GetVendorData(string phrase)
    {
        string strJsonData = "";
        try
        {
            Assignment ObjSAPAssign = new Assignment();
            DataTable dt = ObjSAPAssign.GetVendorList(phrase);               
            strJsonData = JsonConvert.SerializeObject(dt, Formatting.None);                
        }
        catch (Exception ex)
        {
            ApplicationLog.Error("Error", "GetVendorData", ex.Message);
            ErrorLog.HandleErrorLog("", "", "GetVendorData", ex.Message);
        }
        return Json(strJsonData);
    }
Nad
  • 4,605
  • 11
  • 71
  • 160

2 Answers2

2

Your server code:

    string strJsonData = "";
    try
    {
        Assignment ObjSAPAssign = new Assignment();
        DataTable dt = ObjSAPAssign.GetVendorList(phrase);               
        strJsonData = JsonConvert.SerializeObject(dt, Formatting.None);                
    }
    catch (Exception ex)
    {
        ApplicationLog.Error("Error", "GetVendorData", ex.Message);
        ErrorLog.HandleErrorLog("", "", "GetVendorData", ex.Message);
    }
    return Json(strJsonData);

You build the vendor list in dt, and then you use JsonConvert.SerializeObject() to build the response JSON. However, you then serialize it again in that last call to Json(). It should be plain

    return strJsonData;

That's why you get [ as the first "element": the autocomplete plugin is iterating through your JSON as a string. If you change that return statement, it will properly receive your actual table.

edit — I'm pretty sure that the above describes the problem, but my suggestion won't work because that strJsonData is the wrong data type (not JsonResult). Based on this other question I think this might work: don't use JsonConvert.SerializeObject. Instead, use plain Json():

    DataTable dt;
    try
    {
        Assignment ObjSAPAssign = new Assignment();
        dt = ObjSAPAssign.GetVendorList(phrase);               

    }
    catch (Exception ex)
    {
        ApplicationLog.Error("Error", "GetVendorData", ex.Message);
        ErrorLog.HandleErrorLog("", "", "GetVendorData", ex.Message);
    }
    return Json(dt, JsonRequestBehavior.AllowGet);                

(Note that I don't really know C# - the point is that you have to use Json() to get JsonResult from the DataTable.)

Now once that's sorted out, and the autocomplete plugin is receiving the array properly, the next thing to decide is what to do with that getValue() function. The plugin expects to be dealing with strings. In your code, you have that function return an object, and that's just going to confuse the plugin.

I'm not sure what you need for the larger application, but the function could do something like this:

      getValue: function(element) {
        return element.VENDORNAME + " - " + element.VENDORCODE;
      }
Pointy
  • 405,095
  • 59
  • 585
  • 614
  • Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/190225/discussion-on-answer-by-pointy-json-string-from-server-side-not-coming-properly). – Bhargav Rao Mar 18 '19 at 08:00
  • @BhargavRao: did all our discussions deleted ? – Nad Mar 18 '19 at 09:45
1

The error was that you were serializing your DataTable twice, once by JsonConvert.SerializeObject() and the other by Json() method.


Make a model class like this:

public class VendorData 
{ 
    public string VENDORNAME { get; set; } 
    public string VENDORCODE { get; set; } 
}

Here's the modified action method

[HttpPost] 
public JsonResult GetVendorData(string phrase) 
{ 
    try 
    { 
        Assignment ObjSAPAssign = new Assignment(); 
        DataTable dt = ObjSAPAssign.GetVendorList(phrase); 
        List<VendorData> vendorList = dt.AsEnumerable().Select(row => new VendorData 
        { 
            VENDORNAME = row.Field<string>("VENDORNAME"), 
            VENDORCODE = row.Field<string>("VENDORCODE") 
        }).ToList();

        // Serializing only once 
        return Json(vendorList, JsonRequestBehavior.AllowGet); 
    } 
    catch (Exception ex) 
    { 
        ApplicationLog.Error("Error", "GetVendorData", ex.Message); 
        ErrorLog.HandleErrorLog("", "", "GetVendorData", ex.Message); 
        return Json(new object(), JsonRequestBehavior.AllowGet); 
    } 
}

and finally in the client side:

var autocompleteOptions = { 

url: function (phrase) { 
    return AppConfig.PrefixURL + 'App/GetVendorData'; 
}, 

getValue: "VENDORNAME", 

template: { 
    type: "description", 
    fields: { 
    description: "VENDORCODE" 
    } 
}, 

list: { 
    match: { 
        enabled: true 
    } 
}, 

ajaxSettings: { 
    dataType: "json", 
    method: "POST", 
    data: { 
        dataType: "json", 
    } 
}, 

preparePostData: function (data) { 
    data.phrase = $("#txtAssignVendor").val(); 
    return data; 
}, 

requestDelay: 400 
};
Kunal Mukherjee
  • 5,775
  • 3
  • 25
  • 53
  • 1
    Thanks Kunal mate, I will try it on Monday and let u know.. really appreciating your efforts. Upvote :) – Nad Mar 16 '19 at 18:52
  • the first one I tried and its returning it as `{ "VENDORNAME": "ABC", "VENDORCODE": "1234"}` but when I try to debug in client side i get it as `(2) [Array(1), Array(1)]` but nothing inside that array :( – Nad Mar 18 '19 at 05:24
  • are u their ?? need to discuss on this – Nad Mar 18 '19 at 07:09
  • @BN what are you getting as response from the API ? – Kunal Mukherjee Mar 18 '19 at 07:16
  • response in client side is : - `(2) [Array(1), Array(1)]`. but json respnse is `{ "VENDORNAME": "ABC", "VENDORCODE": "1234"}` – Nad Mar 18 '19 at 07:19
  • @BN check in your client side are there JSON.stringify calls written anywhere ? – Kunal Mukherjee Mar 18 '19 at 07:21
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/190224/discussion-between-b-n-and-kunal-mukherjee). – Nad Mar 18 '19 at 07:22