I have this controller function that returns cpu stats:
public ActionResult GetStats()
{
Random rand = new Random();
ViewData["cpu_temp"] = rand.Next(0, 100) + "%";
return View();
}
And with a view it works 100%. Bu tI’m wondering if I could shorten the process, and just do something like:
public ActionResult GetStats()
{
Random rand = new Random();
something.writeline(rand.Next(0, 100) + "%");
}
Just so I can create controllers and not care about views for simple simple simple output 😀
FIX, after a tip by Jamie Dixon i came up with this solution:
public ActionResult GetStats()
{
Random rand = new Random();
ViewData["cpu_temp"] = rand.Next(0, 100) + "%";
return Json(ViewData, JsonRequestBehavior.AllowGet);
}
Works as intended 😀
It all depends on where you want to view the data.
If you want to view the data in your web browser through a web page then you’ll need to return a view.
If you just want to see the data you could output it to the debug console with
Alternatively you could send it to the browser in any number of formats that can be downloaded by the user (JSON, XML, Text file) that won’t require a view.
The key point here is that if you want the user to view the information in their browser in a way that’s likely to show up for them, you’re going to want to use a View.
UPDATE
To return a JSON object you can simply
return JSON(object).