I need to pass a List based on a Model from one Controller Method to another. MailList is used to extract and filter data from a Model (Family), the other CreateMailingList saves the outcome to another Model (Contributie).
The Model FilterListVM is a ViewModel that includes the List<Familie>. When Redirecting the List is empty, where it should contain three records.
As an alternative, I have tried to use TempData to send the List, but than I got the Errormessage: InvalidOperationException: The 'Microsoft.AspNetCore.Mvc.ViewFeatures.Infrastructure.DefaultTempDataSerializer' cannot serialize an object of type 'System.Collections.Generic.List1[DrieHamersV4.Models.Familie]'.
The -simplified- controllerMethod looks as follows:
public async Task<IActionResult> MailingList(FilterListVM contributieLijst)
{
(...) // several variables that filter the data
(...)
string flexDefault = contributieLijst.FlexDefault;
int? contributieJaar = contributieLijst.ContributieJaar;
bool save = contributieLijst.Save;
string message = contributieLijst.Message;
var fList = contributieLijst.Ffamilie;
//************** Getting the Data and Filters for Standard Lists
switch (flexDefault)
{
case "contributie":
fList = await _context.Familie
.OrderBy(f => f.Roepnaam).ToListAsync();
break;
case (...)
break;
default:
fList = contributieLijst.Ffamilie; //previous selection
break;
}
}
contributieLijst.Ffamilie = fList; //fList contains 3 records
//******* Redirects to the next Method
if (save == true)
{
TempData["mailList"] = fList.ToList(); //gives an ErrorMEssage
return RedirectToAction("CreateMailingList", contributieLijst);
}
return View(contributieLijst);
}
public async Task<IActionResult> CreateMailingList(FilterListVM contributielijst)
{
var contributieJaar = contributielijst.ContributieJaar; // This works fine
//var mailingList = (List<Familie>)TempData["mailList"];
var mailingList = contributielijst.Ffamilie; //This is now empty
(...)
The ViewModel FilterListVM
public class FilterListVM
{
public bool? Fovl { get; set; }
public string Fstaak { get; set; }
public string Fgeslacht { get; set; }
public bool? Fbloedverwant { get; set; }
public string Fland { get; set; }
public bool? Femail { get; set; }
public bool? Ftelefoon { get; set; }
public int? FleeftijdVan { get; set; }
public int? FleeftijdTot { get; set; }
public bool? Fcorrespondentie { get; set; }
public string SortColumn { get; set; }
public string SortOrder { get; set; }
public string FlexDefault { get; set; }
public bool ExportToggle { get; set; }
public string SearchString { get; set; }
public string CurrentFilter { get; set; }
public bool Reset { get; set; } = false;
public int? ContributieJaar { get; set; }
public bool Save { get; set; } = false;
public string Message { get; set; }
public List<Familie> Ffamilie { get; set; }
}
}
You can serialize the list to json string before adding to TempData:
using System.Text.Json;
...
TempData["mailList"] = JsonSerializer.Serialize(fList);
And then in your other action:
var mailList = JsonSerializer.Deserialize<List<Familie>>(TempData["mailList"].ToString());
I tried as you mentioned and repeated your error in my case,
Models:
public class FilterListVM
{
public FilterListVM()
{
Ffamilie = new List<Familie>();
}
public string Message { get; set; }
public List<Familie> Ffamilie { get; set; }
}
public class Familie
{
public int Id { get; set; }
public string Description { get; set; }
}
in Controller:
public IActionResult SomeAction()
{
var familie1 = new Familie() { Id = 1, Description = "D1" };
var familie2 = new Familie() { Id = 2, Description = "D2" };
var familielist = new List<Familie>() { familie1, familie2, familie1 };
var vm = new FilterListVM() { Message = "hi" };
vm.Ffamilie = familielist;
return RedirectToAction("AnotherAction", routedic1);
}
public IActionResult AnotherAction(FilterListVM vm)
{
return Ok();
}
The Result:
UrL:
Then I tried to create a new RouteValueDictionary and add the codes:
var routedic = new RouteValueDictionary();
Type vmtype = typeof(FilterListVM);
foreach (var property in vmtype.GetProperties())
{
routedic.Add(property.Name, vmtype.GetProperty(property.Name).GetValue(vm));
}
return RedirectToAction("AnotherAction", vm)
it performed same as before,so in my opinion,the designer may not consider passing complex model contains a list to route value for the length of url is limited;
Then I tried hard coding as below:
var routedic1 = new RouteValueDictionary(vm);
routedic1.Remove("Ffamilie");
for (int i = 0; i < vm.Ffamilie.Count; i++)
{
var key1 = string.Format("Ffamilie[{0}].Id", i.ToString());
routedic1.Add(key1, vm.Ffamilie[i].Id);
var key2 = string.Format("Ffamilie[{0}].Description", i.ToString());
routedic1.Add(key2, vm.Ffamilie[i].Description);
}
return RedirectToAction("AnotherAction", routedic1);
This time it bind the model successfully,
After trying to mix a fileupload and json data in postman i finally found a method where it is possible to send them both in the same request. Therefore, I have moved my json data to a Key in Postman, so that it becomes possible to send files as well using form-data (Picture below).
Within the value I have JSON data as following:
{
"WorkshopEmail":"workshopemail",
"WorkshopContactperson":"workshopcontactperson",
"WorkshopCellphone":"workshopcellphone",
"Service":[
{
"service":"Claim Airbag",
"RequestTypeId":"1",
"DamageDate":"2021-05-03",
"DamageKilometerreading":"213",
"LatestServiceDate":"2021-05-03",
"LatestServiceKilometer":"1223",
"WorkshopDiagnos":"diagnos workshop",
"CarOwnerDescription":"carownerdescription",
"CategoryId":"25",
"works":[
{
"title":"arbete 1 airbag",
"chargePerHour":"11",
"hours":"12",
"price":"132.00",
"id":"13926"
},
{
"title":"arbete2 airbag",
"chargePerHour":"1",
"hours":"2",
"price":"2.00",
"id":"13927"
},
{
"title":"part1 airbag",
"pricePerUnit":"100",
"quantity":"1",
"price":"100.00",
"id":"13928"
},
{
"title":"part2 airbag",
"pricePerUnit":"100",
"quantity":"2",
"price":"200.00",
"id":"13929"
}
]
},
{},
{},
{},
{},
{}
]
}
The empty {} just contains more service types. Now when I send the request in Postman i get a 200 OK and when i debug i can see the following (sorry if the picture is blurry):
¨
However, my database does not get updated with these values. Here's the class for inserting data into the tables:
public async Task<bool> AddRequest(Request model, List<IFormFile> file, [FromForm] string jsonData)
{
bool CreateRequest = true;
int requestID = 0;
int claimID = 0;
//bool country = true;
//First Create the Request
foreach (Service item in model.Service)
{
//First Create the Request
if (CreateRequest)
{
var parameters = new DynamicParameters();
parameters.Add("WorkshopEmail", model.WorkshopEmail);
parameters.Add("WorkshopContactperson", model.WorkshopContactperson);
parameters.Add("WorkshopCellphone", model.WorkshopCellphone);
parameters.Add("DamageDate", model.DamageDate);
parameters.Add("LatestServiceDate", model.LatestServiceDate);
parameters.Add("LatestServiceKilometer", model.LatestServiceKilometer);
parameters.Add("DamageKilometerreading", model.DamageKilometerreading);
parameters.Add("CurrentKilometerreading", model.CurrentKilometerreading);
parameters.Add("CarOwnerDescription", model.CarOwnerDescription);
parameters.Add("WorkshopDiagnos", model.WorkshopDiagnos);
parameters.Add("AmountIncVat", model.AmountIncVat);
try
{
var requestIDenum = await _sqlconnection.QueryAsync<int>($#"INSERT INTO [dbo].[Request]
(WorkshopEmail,WorkshopContactperson,WorkshopCellphone,DamageDate,LatestServiceDate,
LatestServiceKilometer,DamageKilometerreading,CurrentKilometerreading,
CarOwnerDescription,WorkshopDiagnos,AmountIncVat)
VALUES
(#WorkshopEmail,#WorkshopContactperson,#WorkshopCellphone,#DamageDate,#LatestServiceDate,
#LatestServiceKilometer,#DamageKilometerreading,#CurrentKilometerreading,
#CarOwnerDescription,#WorkshopDiagnos,#AmountIncVat);SELECT SCOPE_IDENTITY();",parameters);
requestID = requestIDenum.First();
CreateRequest = false;
}
catch(Exception ex)
{
int hej = 0;
}
}
if (item.fileuploadresults != null)
{
foreach (FileUploadResult f in item.fileuploadresults)
{
var parameters = new DynamicParameters();
parameters.Add("file", f.filename);
var filemessage = await _sqlconnection.QueryAsync<int>($#"INSERT INTO [dbo].[OptionalFile] ([FileName])
VALUES (#file); SELECT SCOPE_IDENTITY();", parameters);
int FileMessageID = filemessage.First();
await _sqlconnection.QueryAsync<int>($#"INSERT INTO[dbo].[ClaimCrossOptionalFile]
(ClaimID,FileID)
VALUES
({claimID},{FileMessageID});");
}
}
return true;
//return list;
}
Controller:
[HttpPost]
public async Task<IActionResult> AddRequest(List<IFormFile> file, [FromForm] string jsonData)
{
// if (!ModelState.IsValid)
// {
Request request = JsonConvert.DeserializeObject<Request>(jsonData);
try
{
//await _request.AddRequest(request);
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
return Ok();
}
Interface:
Task<bool> AddRequest(Request model, List<IFormFile> file, [FromForm] string jsonData);
Sidenote: This is part of the code, as i've tried to keep it short, so perhaps some } or something is missing here, but there's no problem. If i should add the whole code i could perhaps send it in a link or something similar, as it would be a lot to upload here.
However, I do not now how to proceed with this issue at the moment. I've not worked with form-data much before, at least not with passing json as a value. Perhaps there's something I'm missing/have to do in the controller with the json data? I've tried looking for solutions but I've gotten stuck here. The only issue is that the database does not get updated.
Update, the model:
public class Work
{
//base for claim
public string title { get; set; } = "";
public string chargePerHour { get; set; } = "";
public string hours { get; set; } = "";
public string price { get; set; } = "";
public string id { get; set; } = "";
public string pricePerUnit { get; set; } = "";
public string quantity { get; set; } = "";
//service
public int rentreasonId { get; set; } = -1;
public int rentservicecartypeId { get; set; } = -1;
//tyres
public int tireserviceId { get; set; } = -1;
public IList<TireType> tireTypes { get; set; }
public IList<Labour> labours { get; set; }
public DateTime DateFrom{ get; set; } = DateTime.Parse("1753-01-01");
public DateTime DateTo { get; set; } = DateTime.Parse("1753-01-01");
//Insurance
public string totalAmount { get; set; }
public string requestInsuranceVatID { get; set; }
public string vat { get; set; } = "0.0";
public string totalExclVat { get; set; }="0.0";
public string totalIncVat { get; set; }="0.0";
}
public class Labour
{
public string title { get; set; } = "";
public string chargePerHour { get; set; } = "";
public string hours { get; set; } = "";
public string price { get; set; } = "";
}
public class TireType
{
public string quantity { get; set; } = "";
public string brand { get; set; } = "";
public string model { get; set; } = "";
public string pricePerUnit { get; set; } = "";
public string price { get; set; } = "";
public string tireTypeId { get; set; } = "";
public string widthID { get; set; } = "";
public string heightID { get; set; } = "";
public string diameterID { get; set; } = "";
}
public class Request
{
public string WorkshopEmail { get; set; } = "";
public string WorkshopContactperson { get; set; } = "";
public string WorkshopCellphone { get; set; } = "";
public int AmountIncVat { get; set; } = 0;
#region Claim
public DateTime DamageDate { get; set; } = DateTime.Parse("1753-01-01");
public DateTime LatestServiceDate { get; set; } = DateTime.Parse("1753-01-01");
public int LatestServiceKilometer { get; set; } = 0;
public int DamageKilometerreading { get; set; } = 0;
public int CurrentKilometerreading { get; set; } = 0;
public string CarOwnerDescription { get; set; } = "";
public string WorkshopDiagnos { get; set; } = "";
//public string OptionalMessage { get; set; } = "";
#endregion
public IList<Service> Service { get; set; }
}
public class TireTread
{
public string tireserviceId { get; set; } = "";
public string leftfront { get; set; } = "";
public string rightfront { get; set; } = "";
public string leftrear { get; set; } = "";
public string rightrear { get; set; } = "";
public string added1 { get; set; } = "";
public string added2 { get; set; } = "";
public string added3 { get; set; } = "";
public string added4 { get; set; } = "";
public string added5 { get; set; } = "";
}
public class TireMessage
{
public int tireserviceId { get; set; }
public string message { get; set; }
}
public class Service
{
// [JsonProperty("ServiceId")]
public string RequestTypeId { get; set; } = "";
public string CategoryId { get; set; } = "-1";
public string OptionalMessage { get; set; } = "";
public IList<Work> works { get; set; }
public IList<TireTread> treads { get; set; }
public IList<TireMessage> TireMessages { get; set; }
//filuppladdning
public IList<FileUploadResult> fileuploadresults { get; set; }
}
//filuppladdning
public class FileUploadResult
{
//public IFormFile files { get; set; }
public string filename { get; set; }
}
Firstly,the json format does not match the model structure.You need to pass json like this(Pay attention to DamageKilometerreading and LatestServiceKilometer,the type of them are int,so don't use ""):
{
"WorkshopEmail":"workshopemail",
"WorkshopContactperson":"workshopcontactperson",
"WorkshopCellphone":"workshopcellphone",
"DamageDate":"2021-05-03",
"DamageKilometerreading":213,
"LatestServiceDate":"2021-05-03",
"LatestServiceKilometer":1223,
"WorkshopDiagnos":"diagnos workshop",
"CarOwnerDescription":"carownerdescription",
"Service":[
{
"service":"Claim Airbag",
"RequestTypeId":"1",
"CategoryId":"25",
"works":[
{
"title":"arbete 1 airbag",
"chargePerHour":"11",
"hours":"12",
"price":"132.00",
"id":"13926"
},
{
"title":"arbete2 airbag",
"chargePerHour":"1",
"hours":"2",
"price":"2.00",
"id":"13927"
},
{
"title":"part1 airbag",
"pricePerUnit":"100",
"quantity":"1",
"price":"100.00",
"id":"13928"
},
{
"title":"part2 airbag",
"pricePerUnit":"100",
"quantity":"2",
"price":"200.00",
"id":"13929"
}
]
},
{},
{},
{},
{},
{}
]
}
Then try to add public string service { get; set; }="" inService model.
I found a solution, in case anyone else comes across this problem. I needed to modify the controller and add this code:
[HttpPost]
public async Task<IActionResult> AddRequest(List<IFormFile> file, [FromForm] string jsonData)
{
Request request = JsonConvert.DeserializeObject<Request>(jsonData);
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
try
{
await _request.AddRequest(request, file, jsonData);
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
return Ok();
}
Basically adding request (that I deserialize in the begining of the method), and adding the file, and jsonData in an await request, solved the problem. As for the fileuploading, I needed to modify that method as well, to get the filename into the database:
if (file != null)
{
foreach (IFormFile f in file)
{
string filename = Path.GetFileName(f.FileName);
var parameters = new DynamicParameters();
parameters.Add("file", filename);
var filemessage = await _sqlconnection.QueryAsync<int>($#"INSERT INTO
[dbo].[OptionalFile] ([FileName])
VALUES (#file); SELECT SCOPE_IDENTITY();", parameters);
}
}
Changing these to made it possible to send a request containg both the json key value, and multiple files, in the same request.
I am using this example to upload message with attachment to slack:
How to upload any file on Slack via Slack-App in c#
I want to add user mention to the text variable.
I used both format id and name version but it didn't work.
It displays as plain text with no notification to users
parameters3["text"] = "<#userName>";
update:
public class SlackAttachment
{
public string fallback { get; set; }
public string color { get; set; }
public string pretext { get; set; }
public string author_name { get; set; }
public string author_link { get; set; }
public string author_icon { get; set; }
public string title { get; set; }
public string title_link { get; set; }
public string text { get; set; }
public string image_url { get; set; }
public string thumb_url { get; set; }
public string footer { get; set; }
public string mrkdwn_in {get; set;}
public string footer_icon { get; set; }
}
// a slack file class
class SlackFile
{
public String id { get; set; }
public String name { get; set; }
public String permalink_public { get; set; }
public string permalink { get; set; }
}
// reponse from file methods
class SlackFileResponse
{
public bool ok { get; set; }
public String error { get; set; }
public SlackFile file { get; set; }
}
// reponse from message methods
class SlackMessageResponse
{
public bool ok { get; set; }
public String error { get; set; }
public String channel { get; set; }
public String ts { get; set; }
}
this is my caller
public static void salesCongrat(string imgUrl, string msg)
{
string postedMessage = "Outside message text";
var sampleAttachment = new SlackAttachment[]
{
new SlackAttachment {
fallback = "browser cannot display this",
text = "<#UEMTUFSM>",
color = "e5345e",
pretext = "",
author_name = " ",
author_icon = "",
author_link = "",
title = msg,
title_link = "",
mrkdwn_in = "[\"text\"]",
image_url= imgeuURL,
footer = $"Posted at {DateTime.Now.Day}/" +
$"{DateTime.Now.Month}/{DateTime.Now.Year}/ " +
$"{DateTime.Now.Hour}:{DateTime.Now.Minute }",
footer_icon = ""
},
};
var attachmentsJson = JsonConvert.SerializeObject(sampleAttachment);
var data = new NameValueCollection();
data["token"] = myToken;
data["channel"] = channelName;
data["as_user"] = "true";
data["text"] = postedMessage;
data["attachments"] = attachmentsJson;
var client = new WebClient();
var response = client.UploadValues("https://slack.com/api/chat.postMessage", "POST", data);
string responseInString = Encoding.UTF8.GetString(response);
Console.WriteLine(responseInString);
}
file response :
{"ok":true,"channel":"","ts":"","message":{"bot_id":"","type":"message","text":"Outside message text","user":"","ts":"","attachments":[{"author_name":" ","fallback":"browser cannot display this","text":"<#>","title":" ","footer":"Posted at 1\/4\/2019\/ 18:47","id":1,"color":"e5345e"}]}}
Your code is posting the mention ("<#アユ三君>", lets assume its a user ID) in the main message, but not in the attachment as your title suggests.
To include the mention in the attachment you need to put it in the initialization for your attachment object.
Examples:
var sampleAttachment = new SlackAttachment[]
{
new SlackAttachment
{
fallback = "browser cannot display this",
text = "<#U12345678>",
color = "e5345e",
title = msg,
image_url = imgeURL,
footer = $"Posted at {DateTime.Now.Day}"
}
};
Your mention will be empty and shown with a "private user info" tool tip, when Slack can not find the user ID. To double-check that your user ID is valid you can call users.list in your browser to get a list of all existing user Ids. Make sure to use the same token, that you are using in your app.
Example:
https://slack.com/api/users.list?token=MYTOKEN
I am consuming a REST API service. In the service response JSON, there are attribute names that include spaces and reserved words. I'm trying to map it to a C# class, but I can't assign attribute names that are the same as the field names.
Currently, the mapping only succeeds when the JSON attribute and C# class name of a field matches exactly, otherwise the value comes in as null.
Below is the JSON returned from the service:
{
"value": [ {
"accountNo": "JKBXXXXXXXXXVNX1",
"mainSalesPerson": "XXXXX",
"accountName": "XXXXXX",
"ledgerBalance": "-2,298.70",
"T+3": "0.00",
"T+4": "0.00",
"T+5 and Above": "2,298.70",
"riskRatedPortfolioValue": "109,057.50",
"exposure": "106,758.80",
"costToFirm": "",
"incomeToFirm": "14.59",
"costToIncome(%)": "",
"exposure(%)": "2.11",
"O/S Balance": "-2,298.70"
}],
"success": true
}
I have used the following mapping class:
public class CountObject
{
public string value { get; set; }
public string success { get; set; }
}
public class RiskManagementQueryValueObject
{
public string accountNo { get; set; }
public string mainSalesPerson { get; set; }
public string accountName { get; set; }
public string ledgerBalance { get; set; }
[SerializeAs(Name = "T+3")]
public string T3 { get; set; }
[SerializeAs(Name = "T+4")]
public string T4 { get; set; }
[SerializeAs(Name = "T+5 and Above")]
public string T5_and_Above { get; set; }
public string riskRatedPortfolioValue { get; set; }
public string exposure { get; set; }
public string costToFirm { get; set; }
public string incomeToFirm { get; set; }
[SerializeAs(Name = "costToIncome(%)")]
public string costToIncome { get; set; }
[SerializeAs(Name = "exposure(%)")]
public string exposure_per { get; set; }
[SerializeAs(Name = "O/S Balance")]
public string OS_Balance { get; set; }
}
public class RiskManagementQueryHeadertObject
{
public List<RiskManagementQueryValueObject> value { get; set; }
public bool success { get; set; }
}
And this how I talk to the service:
public List<RiskManagementQueryValueObject> getOverdues()
{
List<RiskManagementQueryValueObject> overdues = new List<RiskManagementQueryValueObject>();
var count = 0.0;
try
{
var restProxy = new RESTProxy();
var request = restProxy.initRestRequest("/cam/riskmanagement/1/query/count", Method.POST, new { requestCriteriaMap = new { currency = "LKR" } });
CountObject data = restProxy.Execute<CountObject>(request);
if (data.success.ToString().ToLower() != "true")
return null;
//get the page count
var pageCount = Math.Truncate(count / 300) + 1;
for (int j = 0; j < pageCount; j++)
{
var request2 = restProxy.initRestRequest(string.Format("/cam/riskmanagement/1/query/{0}", (j + 1).ToString()), Method.POST, new { requestCriteriaMap = new { currency = "LKR" } });
RiskManagementQueryHeadertObject data2 = restProxy.Execute<RiskManagementQueryHeadertObject>(request2);
overdues.AddRange(data2.value);
}
}
catch (Exception)
{
overdues = null;
}
return overdues;
}
public class RESTProxy
{
string DEFAULT_HOST = "http://xxx.xxx.xxx.xxx:xxx/";
string DEFAULT_MODULE = "xxx-rest";
string DEFAULT_USER = "xxx:xxx:xxx";
string DEFAULT_PASS = "xxx";
public T Execute<T>(RestRequest request) where T : new()
{
var client = new RestClient(string.Concat(DEFAULT_HOST, DEFAULT_MODULE))
{
Authenticator = new DigestAuthenticator(DEFAULT_USER, DEFAULT_PASS, DEFAULT_HOST)
};
var response = client.Execute<T>(request);
if (response.ErrorException != null)
{
throw response.ErrorException;
}
return response.Data;
}
public RestRequest initRestRequest(string pRestResourceName, Method pRestServiceVerb, object pRestRequestBody)
{
var request = new RestRequest(pRestResourceName, pRestServiceVerb);
request.RequestFormat = DataFormat.Json;
if (pRestRequestBody != null)
{
request.AddBody(pRestRequestBody);
}
return request;
}
}
How can I resolve this and serialize all the fields into my class definition?
Using the JsonProperty attribute worked for me:
Example:
This C# class:
public class Product
{
[JsonProperty(PropertyName = "Name/ + 1")]
public string Name { get; set; }
}
maps to the following javascript object:
var input = {"Name/ + 1": "PostName"};
I solved the issue. I added [DeserializeAs(Name ="")] instead of [SerializeAs(Name ="")]. I just did this in my C# Map class:
public class RiskManagementQueryValueObject
{
public string accountNo { get; set; }
public string mainSalesPerson { get; set; }
public string accountName { get; set; }
public string ledgerBalance { get; set; }
[DeserializeAs(Name = "T+3")]
public string T3 { get; set; }
[DeserializeAs(Name = "T+4")]
public string T4 { get; set; }
[DeserializeAs(Name = "T+5 and Above")]
public string T5_and_Above { get; set; }
public string riskRatedPortfolioValue { get; set; }
public string exposure { get; set; }
public string costToFirm { get; set; }
public string incomeToFirm { get; set; }
[DeserializeAs(Name = "costToIncome(%)")]
public string costToIncome { get; set; }
[DeserializeAs(Name = "exposure(%)")]
public string exposure_per { get; set; }
[DeserializeAs(Name = "O/S Balance")]
public string OS_Balance { get; set; }
}
public class News
{
public string author { get; set; }
public string title { get; set; }
public DateTime timestamp{ get; set; }
public string content { get; set; }
public bool forstudents { get; set; }
public List<link> links { get; set; }
public List<imgs> imgs { get; set; }
}
public class link
{
public string name { get; set; }
public string value { get; set; }
}
public class imgs
{
public string name { get; set; }
public string value { get; set; }
}
This is my Model Description then i connect to the Server
var _esServer = new ElasticSearchServer("http://localhost:9200");
var _esIndex = _esServer.GetIndex("campusoffice");
var news = _esIndex.Get<News>("/news", int.MaxValue);
and it should get everything right but
he doesnt map the name and the value in the list elements
{
"author": "soulseak",
"title": "Awsome",
"timestamp": 20130201,
"content": "Erster",
"forstudents": true,
"links": {
"myhome": "http://test.de"
},
"imgs": {
"myhome": "http://test.de"
}
}
the question is how to tell him what to put in name and value that myhome is in name and the url in value
You can do something like this:
public class User {
public User(string json) {
var jsonObject = Json.Decode(json);
MyName = (string)jsonObject.user.name;
MyTeamName = (string)jsonObject.user.teamname;
MyEmail = (string)jsonObject.user.email;
Players = (DynamicJsonArray) jsonObject.user.players;
}
public string MyName{ get; set; }
public string MyTeamName { get; set; }
public string MyEmail{ get; set; }
public Array Players { get; set; }
}
But would need to assign the values manually.
Example using your model (0 index based only, you would need to write a loop) but using a direct RestFul call:
var url = "http://localhost:9200/campusoffice/news";
var client = new WebClient();
var json = client.DownloadString(url);
var jsonObject = Json.Decode(json);
var links = (DynamicJsonArray) jsonObject.links;
var imgs = (DynamicJsonArray) jsonObject.imgs;
var news = new News
{ author = (string)jsonObject.author,
links = new List<link>() };
var aLink = new link { name = (string)links[0].myhome, value =
(string)imgs[0].myhome };
news.links.Add(aLink);
I typed this roughly without compiling/testing but should give you an idea.