简体   繁体   中英

JSON string from server side not coming properly using ajax jquery

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);
    }

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;
      }

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 
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM