Using jQuery UI Autocomplete in ASP.NET - c#

I am using jQuery UI Autocomplete with ASP.NET like this :
First I am serializing Good names into string array then I passing Array to source of jQuery UI AutoComplete
//PageLoad
tadok.Entities.TList<tadok.Entities.Good> GoodEntites = tadok.Data.DataRepository.GoodProvider.GetAll();
List<string> GoodNames = new List<string>();
foreach (object item_loopVariable in GoodEntites) {
item = item_loopVariable;
GoodNames.Add(string.Format(item.GodTitle));
}
JavaScriptSerializer serializer = new JavaScriptSerializer();
Values = serializer.Serialize(GoodNames);
MarkUp Code :
var availableTags = <%= Values %>
$("#txtGoodAutoComplete").autocomplete({
source: availableTags
});
The object that I am serializing has property with the name ID. How can I serialize ID and storing ID in for example Hidden field on Select item event of autocomplete ?
Update
My main challenge is how to Serialize ID ?

Use select event,
If your object is looks like {'label':'A', 'value':'A', 'ID':'7897975'}
$( ".selector" ).autocomplete({
select: function(event, ui) {
$('#hiddenField').val(ui.item.ID);//Item is your selected object.
}
});
Update:
I have never worked on C#. But there should be any built in JSON parser available.
In java i create JSON format like this,
JSONArray jsonArray = new JSONArray();
JSONObject jsonObject = null;
for(Country country : countries){
jsonObject = new JSONObject();
jsonObject.put("label", country.getName());
jsonObject.put("value", country.getCode());
jsonObject.put("id", country.getId().toString());
jsonArray.add(jsonObject);
}
String json = jsonArray.toJSONString();//The json string will look like, [{'label':'A', 'value':'A', 'id':'7897925'},{'label':'B', 'value':'B', 'id':'7497975'},{'label':'C', 'value':'C', 'id':'7843975'},{'label':'D', 'value':'D', 'id':'7857975'}]
//Your autocomplete source should return something like the above json string
By using Javascript Serializer :
First Add a class :
public class GoodAutoComplete
{
public string label;
public string value;
public string ID;
}
Then Serialize object like this :
tadok.Entities.TList<tadok.Entities.Good> GoodEntites = tadok.Data.DataRepository.GoodProvider.GetAll();
List<GoodAutoComplete> GoodItems = new List<GoodAutoComplete>();
foreach (object item_loopVariable in GoodEntites) {
item = item_loopVariable;
GoodItems.Add(new GoodAutoComplete {
ID = item.GodId,
label = string.Format(item.GodTitle + "{(0)}", item.GodDescrp).Replace("()", ""),
value = string.Format(item.GodTitle + "{(0)}", item.GodDescrp).Replace("()", "")
});
}
JavaScriptSerializer serializer = new JavaScriptSerializer();
Values = serializer.Serialize(GoodItems);

Related

Parsing JSON response from StreamBuilder C#

I'm getting a JSON response back from another website and then building the response from a StreamReader:-
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
response = streamReader.ReadToEnd();
}
The result I'm getting is:-
string response = "{\"d\":\"[{\\\"Animal\\\":\\\"Cat\\\",\\\"Noise\\\":\\\"Meow\\\"},{\\\"Animal\\\":\\\"Dog\\\",\\\"Noise\\\":\\\"Woof\\\"}]\"}";
I've then used the JsonConvert.DeserializeObject(response) to deserialise and then I'm then trying to loop through the results to read the values.. but it's not working whatever I try
dynamic jObj = JsonConvert.DeserializeObject(response);
var arr = jObj; //Tried var arr = jObj.d;
#foreach (var item in arr)
{
….
}
Error: Target type System.Collections.IEnumerable is not a value type or a non-abstract class.
Parameter name: targetType
Your JSON response contains a d property, which value is an array wrapped into string itself.
So, you should parse a d content separately into array, Json.Linq solution is below
string response = "{\"d\":\"[{\\\"Animal\\\":\\\"Cat\\\",\\\"Noise\\\":\\\"Meow\\\"},{\\\"Animal\\\":\\\"Dog\\\",\\\"Noise\\\":\\\"Woof\\\"}]\"}";
var json = JObject.Parse(response);
var array = json["d"];
foreach (var item in JArray.Parse(array.ToString()))
{
Console.WriteLine(item["Animal"]);
}
Solution with deserialization to dynamic object
dynamic json = JsonConvert.DeserializeObject(response);
var array = json?.d;
foreach (var item in JsonConvert.DeserializeObject(array?.ToString()))
{
Console.WriteLine(item?.Animal);
}
It allows you to parse the response without any changes to source JSON
If you printed response, you would see that jObj.d is not an array, but a string. In fact, it looks like the string representation of an array of objects.
It seems that the "d"'s value contains another JSON data. If it is correct and you don't want to touch the JSON format, here is the solution:
string response = "{\"d\":\"[{\\\"Animal\\\":\\\"Cat\\\",\\\"Noise\\\":\\\"Meow\\\"},{\\\"Animal\\\":\\\"Dog\\\",\\\"Noise\\\":\\\"Woof\\\"}]\"}";
dynamic jObj = JsonConvert.DeserializeObject(response);
var arr = JsonConvert.DeserializeObject<D[]>((jObj.d).Value);
foreach (var item in arr)
{
}
........
public class D
{
public string Animal { get; set; }
public string Noise { get; set; }
}

C# Complex class construct Read/Set Value from JSON

I have a problem; I have various (too many) classes, that are linked as Parent/Child
I populate initially my top class while instantiate the others, as follows (works):
TopClass MyClass = new TopClass()
{
Headers = new someHeaders()
{
CorrID = "1234567890",
RequestID = "1234567890",
L_Token = "abcdefghijklmnopqrstuvwxyz"
},
Body = new someBody()
{
access = new AccessHeaders()
{
allPs = "allAcc",
availableAcc = "all"
},
CombinedServiceIndicator = false,
FrequencyPerDay = 10,
ValidUntil = "2020-12-31"
},
ResponseAttributes = new ConsentResponse()
{
myId = String.Empty,
myStatus = String.Empty,
myName = String.Empty,
_links_self_href = String.Empty,
status_href = String.Empty
}
};
The initials values that I populate above rarely change, but the Classes' properties change as the project goes on, and each class ends up having many properties.
I need to parse the properties and set values to any properties that match their name, but I can't seem to figure out why despite following official examples.
(I read the input data from a JSON string I use Newtonsoft - have tried everything out there)
I can't find a way to deserialize the JSON and assign any values to my properties without using the name of the property, i.e. without saying
MyClass.Body.access.allPs = "Hello"
but something like
var json = response.Content.ReadAsStringAsync().Result.ToString();
var a = new { serverTime = "", data = new object[] { } };
var c = new JsonSerializer();
or
if (myresponse.Attributes.GetType().GetTypeInfo().GetDeclaredProperty(key) != null)
myresponse.GetType().GetTypeInfo().GetDeclaredProperty(key).SetValue(myresponse, entry.Value);
//and how do I read the value, parse my TopClass and assign the value to correct property?
Could someone help me?
Values for the properties will get automatically assigned if the JSON is having the correct structure as per the class mentioned above.
Something like:
{
"Body":
"access:
{
"allPs" = "required value"
}
}
Then you can use:
var result = JsonConvert.DeserializeObject < TopClass > (json );

Jquery Post JsonString to c#. How do I parse it

I have a Json here and post it to the server.
newJson.push({ Klasse_Id: parseInt(key), MaxTeilnehmer: value.MaxTeilnehmer });
$http.post('#Url.Content("~/Gw2RaidCalender/SaveEvent")', {
model: saveEventObject,
klassenModel: JSON.stringify(newJson)
}).then(function successCallback(result) {
console.log(result.data);
}),
function errorCallback(result) {
console.log(result.data);
};
Now in my C# code i have this
public string SaveEvent(EventModel model, string klassenModel)
{
JObject result = JObject.Parse(klassenModel);
Now i get this Error
Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray.
It looks like its not an valid Json string !?
"[{\"Klasse_Id\":1,\"MaxTeilnehmer\":2}]"
But I checked it on https://jsonlint.com/ and it says its valid.
I want to get the values out of this Json.
EDIT:
I solved it and now I can save the data
var jsonKlassen = JArray.Parse(klassenModel);
foreach (JObject content in jsonKlassen.Children<JObject>())
{
int klasse_Id = (int)content.Property("Klasse_Id").Value;
int maxTeilnehmer = (int)content.Property("MaxTeilnehmer").Value;
var klassenmodel = new Klasse2EventModel
{
Klasse_Id = klasse_Id,
MaxTeilnehmer = maxTeilnehmer,
Event_Id = newEventId
};
_db.Klasse2EventModel.Add(klassenmodel);
_db.SaveChanges();
}
Because this JSON string contains an array. Try this:
var result = JArray.Parse(klassenModel);

In MVC I want to create ViewData with JSON from controller and use it in view for google chart

In below way in controller I am creating list and converting it into JSON serialization format
List<Models.EmployeeCounts> coverageOffersCount = new List<Models.EmployeeCounts>();
coverageOffersCount.Add(new EmployeeCounts() { Description = "Not Offered", Count = 10});
coverageOffersCount.Add(new EmployeeCounts() { Description = "Waived", Count = 20});
coverageOffersCount.Add(new EmployeeCounts() { Description = "Enrolled", Count = 30});
JavaScriptSerializer serializer = new JavaScriptSerializer();
ViewData["JsonCoverageCounts"] = serializer.Serialize(coverageOffersCount);
Now, I want to use this created ViewData into View
If you want to read and store it to a javascript variable, you can do this
var itemArray = #Html.Raw(ViewData["JsonCoverageCounts"]);
//Let's print it in console
console.log(itemArray);
itemArray will be an array of objects, each with a Count and Description property

What is the best way to deserialize Azure Search result to your own model?

Currently what I'm doing is serializing the JsonResult.Data then Deserialized into dynamic variable before looping in each row and get the Document. Is there any way to handle this? Thanks
if (string.IsNullOrWhiteSpace(searchTerm_))
searchTerm_ = "*";
_azureSearch = new AzureSearchService("afindexdev");
JsonResult result = new JsonResult
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = _azureSearch.SearchAssetFactory(searchTerm_).Results
};
string json = JsonConvert.SerializeObject(result.Data);
var resultJsonString = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(json);
foreach (dynamic row in resultJsonString)
{
var associatemItem = new AssociatedItem();
associatemItem.Id = row.Document.Id;
associatemItem.Title = row.Document.Title;
associatemItem.Type = row.Document.Type;
searcResult.AssociatedItems.Add(associatemItem);
}
What about this?
var associatedItem = Newtonsoft.Json.JsonConvert.DeserializeObject< List < AssociatedItem > >(json);
That way you don't have to make your object yourself.
You can define your model with properties which you want to deserialize with attribute [SerializePropertyNamesAsCamelCase]. This attribute is included to Microsoft.Azure.Search library. After that, all you need to do is to define your model in search generic - like this Hotel class
var sp = new SearchParameters();
if (!String.IsNullOrEmpty(filter))
{
sp.Filter = filter;
}
DocumentSearchResult<Hotel> response = indexClient.Documents.Search<Hotel>(searchText, sp);
You can find more info here

Categories

Resources