Converting a dynamic Variable to List<model> or array - c#

I want to send this Array with Ajax to api :
var receipt = Array();
receipt = [
{ 'Service': 'Saab', 'Order': '20' },
{ 'Service': 'Volvo', 'Order': '12' },
{ 'Service': 'BMW', 'Order': '25' }
];
And this is my Ajax body :
var r = JSON.stringify(receipt);
$.ajax({
type: "POST",
dataType: "Json",
contentType: "application/json; charset=utf-8",
data: r,
url: "api/Receipt",
success: function (result) {
// To Do
console.info(result);
},
error: function (result) {
console.info(result);
}
});
And this is what i get as Json :
{[
{
"Service": "Saab",
"Order": "20"
},
{
"Service": "Volvo",
"Order": "12"
},
{
"Service": "BMW",
"Order": "25"
}
]}
And i catch them in api side Like this :
[Route("api/Receipt")]
[WebMethod]
public string Receipt_Turn(object obj)
{
dynamic dyn = JsonConvert.DeserializeObject(obj.ToString());
if (dyn != null)
{
return dyn[1].ToString();
}
else
{
return "false";
}
}
And it works, the part return dyn[1].ToString() returns second record of my Array. But i want to convert this dynamic variable to a list or array of a model .
Here is my model :
[Serializable()]
public class Receipt
{
public string Service { get; set; }
public string Order { get; set; }
}
I want to act with it like this :
string serv = receipt[1].Service;
How can i do it ?
Thanks...

Delete the Array Part in Your JS Script and Write it Like this :
var receipt = [
{ 'Service': 'Saab', 'Order': '20' },
{ 'Service': 'Volvo', 'Order': '12' },
{ 'Service': 'BMW', 'Order': '25' }
];
in this shape you are sending an Object. in your code i guess you are sending an JArray So it Will make some Problems in Converting from JArray to another Type .
in your API Side , Edit Your Code As Below :
public string Receipt_Turn(object r)
{
//important Line Here
List<Receipt> rr = JsonConvert.DeserializeObject<List<Receipt>>(r.ToString());
if (rr != null)
{
return rr[1].ToString();
}
else
{
return "false";
}
}
as you can see, we get it Like an Object and then we will be able to Get Ready your DeserializeObject part Like i mentioned.
you most declare a List of your Model, and after part DeserializeObject add that Type You want to Convert it to.
here Cause we Declared List<Receipt> , we should convert our DeserializeObject to it, so we add <List<Receipt>> after DeserializeObject.
and Finally you can use it Like You wish .
string serv = rr[1].Service;

Assuming you are using .NET Core, it should be able to bind it automatically if you do something like this:
```
[Route("api/Receipt")]
[WebMethod]
public string Receipt_Turn(List<Receipt> receipts)
{
if (receipts != null)
{
return "seomthing";
}
else
{
return "false";
}
}
```

Related

Pass 2 different data types with jQuery to HttpHandler

Is it possible to pass 2 data types to the HttpHandler in a Webhandler
$.ajax({
type: "POST",
url: "FileHandler.ashx",
contentType:false,
processData: false,
data: {
data: newData,
pathname:"~/pathname/"
},
success: function (result) {
alert('success');
},
error: function () {
alert("There was error uploading files!");
}
});
The RequestPayload in the POST is [object object], is there documentation on how I can parse that object?
Hi Create a new model with all the props including the pathname prop
public class HandlerModel
{
public datatype dataprop1 {get;set;}
public datatype dataprop2 {get;set;}
public datatype dataprop3 {get;set;}
public datatype dataprop4 {get;set;}
public string pathname {get;set;}
}
then in your ashx file
public class QueryStringHandler : IHttpHandler
{
public void ProcessRequest (HttpContext context)
{
//set the content type, you can either return plain text, html text, or json or other type
context.Response.ContentType = "text/plain";
//deserialize the object
UserInfo objUser = Deserialize<HandlerModel>(context);
//now we print out the value, we check if it is null or not
if (objUser != null) {
context.Response.Write("Go the Objects");
} else {
context.Response.Write("Sorry something goes wrong.");
}
}
public T Deserialize<T>(HttpContext context) {
//read the json string
string jsonData = new StreamReader(context.Request.InputStream).ReadToEnd();
//cast to specified objectType
var obj = (T)new JavaScriptSerializer().Deserialize<T>(jsonData);
//return the object
return obj;
}
}

Using Facets in the Aggregation Framework C#

I would like to create an Aggregation on my data to get the total amount of counts for specific tags for a collection of books in my .Net application.
I have the following Book class.
public class Book
{
public string Id { get; set; }
public string Name { get; set; }
[BsonDictionaryOptions(DictionaryRepresentation.Document)]
public Dictionary<string, string> Tags { get; set; }
}
And when the data is saved, it is stored in the following format in MongoDB.
{
"_id" : ObjectId("574325a36fdc967af03766dc"),
"Name" : "My First Book",
"Tags" : {
"Edition" : "First",
"Type" : "HardBack",
"Published" : "2017",
}
}
I've been using facets directly in MongoDB and I am able to get the results that I need by using the following query:
db.{myCollection}.aggregate(
[
{
$match: {
"Name" : "SearchValue"
}
},
{
$facet: {
"categorizedByTags" : [
{
$project :
{
Tags: { $objectToArray: "$Tags" }
}
},
{ $unwind : "$Tags"},
{ $sortByCount : "$Tags"}
]
}
},
]
);
However I am unable to transfer this over to the .NET C# Driver for Mongo. How can I do this using the .NET C# driver?
Edit - I will ultimately be looking to query the DB on other properties of the books as part of a faceted book listings page, such as Publisher, Author, Page count etc... hence the usage of $facet, unless there is a better way of doing this?
I would personally not use $facet here since you've only got one pipeline which kind of defeats the purpose of $facet in the first place...
The following is simpler and scales better ($facet will create one single potentially massive document).
db.collection.aggregate([
{
$match: {
"Name" : "My First Book"
}
}, {
$project: {
"Tags": {
$objectToArray: "$Tags"
}
}
}, {
$unwind: "$Tags"
}, {
$sortByCount: "$Tags"
}, {
$group: { // not really needed unless you need to have all results in one single document
"_id": null,
"categorizedByTags": {
$push: "$$ROOT"
}
}
}, {
$project: { // not really needed, either: remove _id field
"_id": 0
}
}])
This could be written using the C# driver as follows:
var collection = new MongoClient().GetDatabase("test").GetCollection<Book>("test");
var pipeline = collection.Aggregate()
.Match(b => b.Name == "My First Book")
.Project("{Tags: { $objectToArray: \"$Tags\" }}")
.Unwind("Tags")
.SortByCount<BsonDocument>("$Tags");
var output = pipeline.ToList().ToJson(new JsonWriterSettings {Indent = true});
Console.WriteLine(output);
Here's the version using a facet:
var collection = new MongoClient().GetDatabase("test").GetCollection<Book>("test");
var project = PipelineStageDefinitionBuilder.Project<Book, BsonDocument>("{Tags: { $objectToArray: \"$Tags\" }}");
var unwind = PipelineStageDefinitionBuilder.Unwind<BsonDocument, BsonDocument>("Tags");
var sortByCount = PipelineStageDefinitionBuilder.SortByCount<BsonDocument, BsonDocument>("$Tags");
var pipeline = PipelineDefinition<Book, AggregateSortByCountResult<BsonDocument>>.Create(new IPipelineStageDefinition[] { project, unwind, sortByCount });
// string based alternative version
//var pipeline = PipelineDefinition<Book, BsonDocument>.Create(
// "{ $project :{ Tags: { $objectToArray: \"$Tags\" } } }",
// "{ $unwind : \"$Tags\" }",
// "{ $sortByCount : \"$Tags\" }");
var facetPipeline = AggregateFacet.Create("categorizedByTags", pipeline);
var aggregation = collection.Aggregate().Match(b => b.Name == "My First Book").Facet(facetPipeline);
var output = aggregation.Single().Facets.ToJson(new JsonWriterSettings { Indent = true });
Console.WriteLine(output);

Post Json List of Object to webmethod in C#?

I am trying to post List of object (or array of object) to c# Webmethod. I am understanding how to receive as parameter in the method and convert into local List of object?.
for (var i = 0; i < usersInfo.length; i++) {
user = {
UserName : usersInfo[i].UserName,
Email : usersInfo[i].Email,
Status : status
};
users.push(user);
}
var results = "";
$('#lblError').val('');
if (users.length > 0) {
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'UserValidation.aspx/ShowResults',
data: "{'UsersInfo':'" + JSON.stringify(users) + "'}",
async: false,
success: function (data) {
results = data.d;
$('#lblError').val(results);
},
error: function (xhr, status, error) {
var exception = JSON.parse(xhr.responseText);
alert(exception.Message);
}
});
}
Code behind
[WebMethod]
public static void ShowResults(//Here how receive list object from javascript)
{
//convert parameter to List<UsersInfo>
}
public partial class UsersInfo
{
public string UserName { get; set; }
public string Email { get; set; }
public string Status { get; set; }
}
Try to replace this line
data: JSON.stringify({ UsersInfo: users}),
James you are the right track; you need to define the correct type for the ShowResults parameter so that the binding will work and bind the incoming json to your UsersInfo class.
Your UsersInfo class appears to be a simple POCO so should bind without any custom binding logic :
[WebMethod]
public static void ShowResults(List<UsersInfo> UsersInfo)
{
//No need to convert
}

Return JSON from MVC via AJAX

I've been using a hard coded JSON object:
var resuts = [{id: 1, Code: "Code A"}, {id: 2, Code: "Code B"}]
I'm then iterating this object calling the items by index and using .length:
for (var i = 0; i < resuts.length; i++) {
console.log('id:' + resuts[i].id + ' | ' + 'Code:' + resuts[i].Code}
Now I want to pull this data from the server so I created an object to handle the properties and have this action method:
public ActionResult GetResults()
{
string json = JsonConvert.SerializeObject(new
{
results = new List<Question>()
{
new Question { id = 1, Code = "Code A},
new Question { id = 1, Code = "Code B}
}
});
return Json(new { data = json }, JsonRequestBehavior.AllowGet);
}
I'm calling it with this AJAX:
function GetResultsJSON() {
$.ajax({
type: 'GET',
url: '/Home/GetResults/',
dataType: 'json',
traditional: true,
success: function (data) {
results = data;
},
error: function (data) {
alert('Error.');
}
})
};
Now my results object contains:
"{" results ":[{" id ":1," Code ":" Code A "},{" id ":1," Code ":" Code B "}]}"
Now I get JavaScript errors when trying to use the length property or call items by index. From what I have read up on, I think my original hard coded object is just an array, however, I have to work differently with the JSON that's returned from my controller.
Can anyone advise on either returning the array format that I was originally working with or the best way to handle the JSON format as it's returned here? I have tried things like
$.each(data, function(i, obj) {
alert(obj.name);
});
but this returns undefined. Any help would be great.
public JsonResult TestAjax(int leagueId)
{
var results = new List<BaseballViewModel>()
{
new BaseballViewModel{ DivisionId = 1},
new BaseballViewModel{ DivisionId = 2}
}.ToList();
return Json(results, JsonRequestBehavior.AllowGet);
}
$.ajax({
url: "/Home/TestAjax",
type: "GET",
data: { leagueId: 5 },
success: function (data) {
// alert(JSON.stringify(data)); show entire object in JSON format
$.each(data, function (i, obj) {
alert(obj.DivisionId);
});
}
});
Instead of:
$.each(data, function(i, obj) {
alert(obj.name);
});
why don't you try:
$.each(data.results, function(i, obj) {
alert(obj.name);
});
If you create a Model class that way :
[Serializable()]
public class MyResponse
{
public int Id {get; set;}
public string Code {get; set;}
}
And that you create a list of "MyResponse"
You will just have to do
return Json(new { data = listOfMyResponse}, JsonRequestBehavior.AllowGet);

Can't get data from GetJson method

Here is my code in Default.aspx:
$(function() {
var dataSource = {};
$("#MainTree,#SubTree").jstree({
"json_data": {
"ajax":{
type: "POST",
async: true,
url: "Default.aspx/GetJson",
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
success: function(msg) {
dataSource = msg;
},
error: function(err) {
alert(err);
},
data: dataSource,
},
},
"plugins": ["themes", "json_data", "ui", "dnd"]
});
});
And here is GetJson method in Default.aspx.cs:
[WebGet(ResponseFormat = WebMessageFormat.Json)]
[System.Web.Services.WebMethod]
public static string GetJson()
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row = null;
DataTable dtEmployee = new DataTable();
dtEmployee.Columns.Add("EmpId", typeof(int));
dtEmployee.Columns.Add("Name", typeof(string));
dtEmployee.Columns.Add("Address", typeof(string));
dtEmployee.Columns.Add("Date", typeof(DateTime));
//
// Here we add five DataRows.
//
dtEmployee.Rows.Add(25, "Rk", "Gurgaon", DateTime.Now);
dtEmployee.Rows.Add(50, "Sachin", "Noida", DateTime.Now);
dtEmployee.Rows.Add(10, "Nitin", "Noida", DateTime.Now);
dtEmployee.Rows.Add(21, "Aditya", "Meerut", DateTime.Now);
dtEmployee.Rows.Add(100, "Mohan", "Banglore", DateTime.Now);
foreach (DataRow dr in dtEmployee.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dtEmployee.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
return serializer.Serialize(rows);
}
EDIT:
This is the result when i check GetJson method respone:
{"d":"[{\"EmpId\":25,\"Name\":\"Rk\",\"Address\":\"Gurgaon\",\"Date\":\"\/Date(1372999726975)\/\"},{\"EmpId\":50,\"Name\":\"Sachin\",\"Address\":\"Noida\",\"Date\":\"\/Date(1372999726975)\/\"},{\"EmpId\":10,\"Name\":\"Nitin\",\"Address\":\"Noida\",\"Date\":\"\/Date(1372999726975)\/\"},{\"EmpId\":21,\"Name\":\"Aditya\",\"Address\":\"Meerut\",\"Date\":\"\/Date(1372999726975)\/\"},{\"EmpId\":100,\"Name\":\"Mohan\",\"Address\":\"Banglore\",\"Date\":\"\/Date(1372999726975)\/\"}]"}
And the result is nothing..It just appeared "..Loading" flashly and then it return blank page..please help me to show what's the problem here is..Thanks a lot.
It seems that you've not read the documentation properly so I would suggest you do that first.
When you use json_data plugin, you need to follow basic structure as shown below and could be found here, that means you need to provide Json data in below format:
{
"data" : "node_title",
// omit `attr` if not needed; the `attr` object gets passed to the jQuery `attr` function
"attr" : { "id" : "node_identificator", "some-other-attribute" : "attribute_value" },
// `state` and `children` are only used for NON-leaf nodes
"state" : "closed", // or "open", defaults to "closed"
"children" : [ /* an array of child nodes objects */ ]
}
Taking response structure into consideration, you need to have server side class as shown below:
public class Emp
{
public EmpAttribute attr { get; set; }
public string data { get; set; }
}
public class EmpAttribute
{
public string id;
public bool selected;
}
And your pagemethod should look alike below:
[WebGet(ResponseFormat = WebMessageFormat.Json)]
[System.Web.Services.WebMethod]
public static List<Emp> GetJson()
{
List<Emp> empTreeArray = new List<Emp>();
Emp emp1 = new Emp()
{
attr = new EmpAttribute(){ id= "25",selected=false},
data = "Nitin-Gurgaon"
};
Emp emp2 = new Emp()
{
attr = new EmpAttribute(){ id="50",selected=false},
data = "Sachin-Noida"
};
empTreeArray.Add(emp1);
empTreeArray.Add(emp2);
return empTreeArray;
}
Your clientside binding code should be like below:
$(function() {
var dataSource = {};
$("#demo1").jstree({
"json_data": {
"ajax":{
"type": "POST",
"url": "Default2.aspx/GetJson",
"contentType": "application/json; charset=utf-8",
"dataType": "json",
success: function(msg) {
return msg.d;
},
error: function(err) {
alert(err);
}
}
},
"plugins": ["themes", "json_data", "ui", "dnd"]
});
});
Notice return msg.d in Success function that is missing from your code.
More examples could be found here
Please go through documentation of any plugin you use next time.
type http://Default.aspx/GetJson directly in browser and check whether correct data is coming or not.
Other two locations where you can add debugging code is
success: function(msg) {
dataSource = msg;
},
error: function(err) {
alert(err);
}
add breakpoints and debug the javascript.
The response is encapsulated in a property called "d". Instead of datasource = msg you should have datasource = msg.d

Categories

Resources