Sunday, June 3, 2018

Call one action returning JSON from another at a .NET Core MVC controller!

"ASP.NET Core 2 and Angular 5" by Valerio De Sanctis calls the "Latest" method (action) at the bottom of this like so from an action in the same controller!

[HttpGet("Random/{num}")]
public IActionResult Random(int num = 10)
{
   var sampleQuizzes = ((JsonResult)Latest(num)).Value as List<QuizViewModel>;
   return new JsonResult(sampleQuizzes.OrderBy(t => Guid.NewGuid()), new
         JsonSerializerSettings()
   {
      Formatting = Formatting.Indented
   });
}

 
 

Things to note:

  1. JsonResult of Microsoft.AspNet.Core.Mvc.JsonResult is used to cast off what it is gleamed from the other action, then a .Value is done off of that, and finally there is a second casting utilizing the "as" keyword.
  2. The return statement has a cool hack for randomizing things in a collection, huh?
  3. This example and the one here use optional parameters, but I do not think these parameters are really optional. I cannot get the routing to work if I just leave off the trailing number when I experiment at the URL line in Microsoft Edge.

No comments:

Post a Comment