My data is being generated at a JsonResult which output is below.
public JsonResult SampleAAA(Guid xxxxx){
//Code ...
return Json(new
{
success = true,
listA,
listB,
}, JsonRequestBehavior.AllowGet);
}
From an ActionResult I need to call that JsonResult and get those lists.
public ActionResult SampleBBB(Guid xxxxx){
var result = SampleAAA(xxxx);
//How can I access 'listA' and 'listB' ?
//Other code ...
Return View();
}
How can I access those lists? I do see result.Data content, but I can't reach those lists to continue my code at Visual Studio.
you can try this code
var result = SampleAAA(xxxx);
var jsonObject = (JObject)result.Value;
bool success = (bool)jsonObject["success"];
and it's much better to use JsonResult
return new JsonResult(new
{
success = true,
listA,
listB,
});
Using .Net 5+ you can do this:
using System.Text.Json;
var doc = JsonDocument.Parse(YOUR_JSON);
var property = doc.RootElement.GetProperty("ListA");
Thanks for all replies. After more research I've managed to solve with the code below.
public ActionResult SampleBBB(Guid xxxxx){
var result = SampleAAA(xxxx);
//Steps to have access to those information:
string stringJson = JsonSerializer.Serialize(result.Data);
var resultString = JObject.Parse(stringJson);
var outputA = resultString["listA"].Value<string>();
//...
}
Related
Having troubles to return json .net core 6.0 C#
I'm using NewtonSoft json library
Obviously I'm doing something wrong...
using NetMQ;
using NetMQ.Sockets;
using Newtonsoft.Json.Linq;
using System.Text;
static JObject j_tmp = new JObject();
private static async Task<IResult> Command1()
{
j_tmp["test"] = "1234";
j_tmp["number"] = 18;
//return Results.Json(j_tmp ); //Doesn;t work, empty body
//return Results.Json(j_tmp.ToString()); //Doesn't work, adds "\r\n" on each break line
return Results.Content(j_tmp.ToString(Newtonsoft.Json.Formatting.None), "application/json; charset=utf-8"); //WORKS
}
when I return JObject object, it appears empty on receiving (frontend)
side
Maybe you want a way to pass the JObject object from contoller to the view ?
If so, you can refer to below demo.
In controller:
static JObject j_tmp = new JObject();
public IActionResult Index()
{
j_tmp["test"] = "1234";
j_tmp["number"] = 18;
ViewBag.j_tmp= j_tmp;
return View(j_tmp);
}
In the view:
#ViewBag.j_tmp
Result:
use this method
private static async Task<JsonResult> Command1()
{
j_tmp["test"] = "1234";
j_tmp["number"] = 18;
//return Results.Json(j_tmp ); //Doesn;t work, empty body
//return Results.Json(j_tmp.ToString()); //Doesn't work, adds "\r\n" on each break line
return Json(new JsonResult(null, new { test = j_tmp["test"], number = j_tmp["number"] }));
}
Assume you are working on ASP.NET Core project (as your question mentioned a GET request) and you are asking how to return a simple json.
The simplest way is to return an anonymous object in your action method.
In your controller:
[HttpGet]
public IActionResult YourAction()
{
return OK(new { test = "1234", number = 18 });
}
Is that what you need?
I'm using a IActionResult (task) to upload a file and i refference that in my controller. What i want to get back is the file name.
Controller ->
var imageLocation = await _imageHandler.UploadImage(image);
ImageHandler ->
public async Task<IActionResult> UploadImage(IFormFile file)
{
var result = await _imageWriter.UploadImage(file);
return new ObjectResult(result);
}
My value is stored in imageLocation, but i have no idea how to access it (i need the "Value" string so i can add it to DB).
I've tried searching for everything, but everyone is using a list. I only need a string here.
Hopefully you guys can help me out. Thanks!
You can cast the result to the desired type and call property
Controller
var imageLocation = await _imageHandler.UploadImage(image);
var objectResult = imageLocation as ObjectResult;
var value = objectReult.Value;
or just refactor the ImageHandler.UploadImage function to return the actual type to avoid having to cast
public async Task<ObjectResult> UploadImage(IFormFile file) {
var result = await _imageWriter.UploadImage(file);
return new ObjectResult(result);
}
and get the value as expected in controller
var imageLocation = await _imageHandler.UploadImage(image);
var value = imageLocation.Value;
Better yet, have the function just return the desired value
public Task<string> UploadImage(IFormFile file) {
return _imageWriter.UploadImage(file);
}
that way you get what is expected when calling the function in the controller.
string imageLocation = await _imageHandler.UploadImage(image);
Just came across a Result.Value from FluentValidation Errors:
ObjectResult? result = (await controller.CreateSomething(InvalidDTO)) as ObjectResult;
List<FluentValidation.Results.ValidationFailure> value = (List<FluentValidation.Results.ValidationFailure>)result.Value;
I have a simple Web Api method which returns a list. I decided as a general project rule, that if the list is empty for a particular userId, we return an Ok() method with empty content.
My web api method looks like following:
[Route("")]
[HttpGet]
public IHttpActionResult GetPersonalList()
{
var result = _facade.Get(_userContext.Get());
if (result == null)
return Ok(); //here is the point
return Ok(new PersonalExpensesReportViewModel(result));
}
Trying to make a 100% of coverage of this method, I wanted to test the scenario that I mentioned, but I could not achieve how to write the assert for the empty content.
[TestMethod]
public void GetPersonalList_NoContent_Ok()
{
//Arrange
_facade.Setup(x => x.Get(_userContext.Object.GetPersonnelNumber(), null)).Returns((PersonalExpensesReport)null);
//Act
var result = _controller.GetPersonalList();
//Assert
var negociatedResult = result as OkResult;
Assert.IsNotNull(result);
// ?? I want something like Assert.IsNull(negociatedResult.Content)
}
Being that I don't have a certain type to make result as OkNegotiatedContentResult which expects T type to be instantiated, I thought about cast as OkResult, but I don't have the 'Content' property in this class.
Does someone know how to proceed in this cases?
Please try to use OkNegotiatedContentResult<T> like:
var result = _controller.GetPersonalList();
var response = result as OkNegotiatedContentResult<PersonalExpensesReportViewModel>;
Assert.IsNotNull(response);
var content = response.Content;
Assert.AreEqual(5, content.Count());
[TestMethod]
public void GetPersonalList_NoContent_Ok()
{
var serviceresponse = new yourresponseobject<yourmodel>{
Message = "what ever response";
Data = null;
};
var service = new Mock<youserviceInterface>(MockBehavior.Strict);
service.Setup(x => x.GetPersonalList()(It.IsAny<string>())).ReturnsAsync(serviceResponse); /// for number of parameters in controller method, add It.IsAny<string>()
//Arrange
_facade.Setup(x => x.Get(_userContext.Object.GetPersonnelNumber(), null)).Returns((PersonalExpensesReport)null);
//Act
var result = _controller.GetPersonalList();
//Assert
var negociatedResult = result as Object;
Assert.IsNotNull(result.value);
Assert.AreEqual(200,result.negociatedResult.statuscode);
}
I am creating Controller to return an object in JSON format.
I want to use Newtonsoft.Json library.
I created two methods:
[HttpGet]
[ActionName("RetrieveTestClassJson")]
public ActionResult RetrieveTestClassJson(int id)
{
TestThing testThing = new TestThing() { Name = "LPL.22.334", Type = TypeTest.Component };
JsonNetResult jsonNetResult = new JsonNetResult();
jsonNetResult.Formatting = Formatting.Indented;
jsonNetResult.ContentType = "application/json";
jsonNetResult.ContentEncoding = Encoding.Unicode;
jsonNetResult.Data = testThing;
return jsonNetResult;
}
[HttpGet]
[ActionName("RetrieveTestClassCase2")]
public TestThing RetrieveTestClassCase2(int id)
{
TestThing testThing = new TestThing() { Name = "LPL.22.334", Type = TypeTest.Component };
return testThing;
}
when I call RetrieveTestClassJson from ajax or browser url I get:
{"ContentEncoding":{"isThrowException":false,"bigEndian":false,"byteOrderMark":true,"m_codePage":1200,"dataItem":null,"encoderFallback":{"strDefault":"�","bIsMicrosoftBestFitFallback":false},"decoderFallback":{"strDefault":"�","bIsMicrosoftBestFitFallback":false},"m_isReadOnly":true},"ContentType":"application/json","Data":{"Name":"LPL.22.334"},"SerializerSettings":{"ReferenceLoopHandling":0,"MissingMemberHandling":0,"ObjectCreationHandling":0,"NullValueHandling":0,"DefaultValueHandling":0,"Converters":[{"CamelCaseText":true,"CanRead":true,"CanWrite":true}],"PreserveReferencesHandling":0,"TypeNameHandling":0,"TypeNameAssemblyFormat":0,"ConstructorHandling":0,"ContractResolver":null,"ReferenceResolver":null,"TraceWriter":null,"Binder":null,"Error":null,"Context":{"m_additionalContext":null,"m_state":0},"DateFormatString":"yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK","MaxDepth":null,"Formatting":0,"DateFormatHandling":0,"DateTimeZoneHandling":3,"DateParseHandling":1,"FloatFormatHandling":0,"FloatParseHandling":0,"StringEscapeHandling":0,"Culture":"(Default)","CheckAdditionalContent":false},"Formatting":1}
When I call RetrieveTestClassCase2 I get normal JSON format.
I removed xml handler for testing purposes for now:
var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
I am puzzled of what is going on.
WebApi already has the Json serializer in the pipeline, http://www.asp.net/web-api/overview/formats-and-model-binding/json-and-xml-serialization, so I think in your method where you are explicitly serializing, the result ends up serialized twice. The second method is what you want unless you remove the json formatter as well.
The reason it's return JSON when you don't do anything, is because MVC has its own build in JSON serialzer. Since this is a
[System.Web.Http.HttpGet]
not
[System.Web.Mvc.HttpGet]
it treats what your sending as data and not as markup. That's why it's returning your object as JSON. It knows that your sending just an object, so it serializes it for you. If you wanted the same functionality in a [System.Web.Mvc.HttpGet], you would return a JsonResult instead of an ActionResult.
var result = new JsonResult();
result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
result.Data = testThing;
I have the following method which is supposed to return a JSONResult so I can use it in an AJAX method with javascript and load autocomplete suggestions for a textbox. I will load this everytime a particular dropdown list changes.
[AcceptVerbs(HttpVerbs.Post), Authorize]
private JsonResult GetSchemaNodeValues(string SchemaNodeId)
{
var query = #"Select ld.""Value""
From ""LookupData"" ld, ""SchemaNode"" sn
Where sn.""LookupTypeId"" = ld.""LookupTypeId""
And sn.""SchemaNodeId"" = '{0}'";
DataSet data = new DataSet();
data = ServiceManager.GenericService.ExecuteQuery(String.Format(query, SchemaNodeId)).Data;
var res = data.Tables[0].AsEnumerable().Select(dr => new
{
Value = dr["Value"].ToString()
});
return JsonConvert.SerializeObject(res);
}
I get the following error under return JsonConvert.SerializeObject(res);
Error 106 Cannot implicitly convert type 'string' to 'System.Web.Mvc.JsonResult'
Is there any way to get past this?
Before this I tried using System.Web.mvc.Controller.Json(res); which returns a JSONResult from an object.
But I couldn't use it because my class is a PageDialog not a Controller so it doesn't have access to Controller's protected internal methods like JSon(). The error I got was that JSon() is inaccessible due to its protection level. The Controller class was locked and I can't make it public or create a workaround so I changed the approach using JsonConvert.SerializeObject(res);
Any suggestions would be extremely welcome.
private dynamic GetSchemaNodeValues(string SchemaNodeId)
{
...
return data.Tables[0].AsEnumerable().Select(dr => new
{
Value = dr["Value"].ToString()
});
}
or
private string GetSchemaNodeValues(string SchemaNodeId)
{
...
var result = data.Tables[0].AsEnumerable().Select(dr => new
{
Value = dr["Value"].ToString()
});
return JsonConvert.SerializeObject(result);
}