Output JSON value in ASP.NET MVC - c#

I´m trying to get single value out of an object array and display it for now inside paragraph tag on my index page.
In my HomeController I have done this
public ActionResult Index()
{
WebClient client2 = new WebClient();
Stream stream = client2.OpenRead("http://localhost/ARN/weatherAPI.json");
StreamReader reader = new StreamReader(stream);
Newtonsoft.Json.Linq.JObject jObject = Newtonsoft.Json.Linq.JObject.Parse(reader.ReadLine());
// instead of WriteLine, 2 or 3 lines of code here using WebClient to download the file
var weatherString = (string)jObject["weather"][0]["main"];
stream.Close();
return View();
I started by creating a new project in Console Application to test it and I ran this lines of code but used Console.Writeline(weatherString) and it gave me exactly the value I needed in the console but now I'm facing the problem to try to show it on the index page with the ASP.NET MVC
Since this piece of code is in my HomeController and my Index.cshtml is elsewhere, is there an easy way for me to output the weatherString variable as an simple text on my index page?
The JSON looks like this:
"weather":[{"id":500,"main":"Rain","description":"light rain","icon":"10d"}]
So I wan't "Rain" to be outputted on my webpage.

You'll probably want it in your ViewBag. In the controller:
ViewBag.WeatherString = weatherString;
then in the view access it with #ViewBag.WeatherString
Alternatively you can use it as the view's model:
return View(weatherString)
and in your view:
model string
but thats pretty overkill

Related

What is the equivalent MVC code for ASP.NET CORE?

In my MVC C# project (NOT THE CORE) i used this successfully:
Index.cshtml:
<script>
#{
var ListVar = Model.TimeToolDataList;
//TimeToolDataList (*it's an object list, ex: NAME = string, VALUE = int)
var SerializedList = new JavaScriptSerializer().Serialize(ListVar);
}//razer code in the script tag ^ by the #{} wrapper
var SerializedListRefined = JSON.parse('"#SerializedList"');
var FinalList = JSON.parse(htmlDecode(SerializedListRefined));</script>
great!!! i can console.log the list and 'see' it's contents, what is the equivalent of this code for ASP.NET CORE project? because when i copy/pasted *along with all the other stuff, it wont run!!!
This cant be used: JavaScriptSerializer()
This cant be used either: JSON.parse(htmlDecode(SerializedListRefined));
Update, instead of JavaScriptSerializer() , this worked:
var jsonStr = JsonSerializer.Serialize(ListVar);
^under #using System.Text.Json;
when running, the console on the browser gives me an 'Uncaught ReferenceError: htmlDecode is not defined' error
try something like the next
to deserialize the object correclty you have to use #HtmlRaw just assuming ListVar is your Model/Object (the object comming from the c# controller)
you can do the next :
var jsoninJS = #Html.Raw(Json.Serialize(Listvar));
that gives you in your var jsoninJS the object that you can print with Console.log(jsoninJS) in javascript.
if you include
#using System.Web you can also decode with C#
using #HttpUtility.HtmlDecode(string)
but you should decode/encode on you print the data, not anywhere else.

Render dynamic HTML with embedded Razor variables using MVC

I have some encoded Html which have any number of 1000s of different Razor variables embedded within it that I have stored and need to retrieve from the database. I want to be able to render this in a MVC/razor view.
Just one simple example of the html saved on the database (it can be more complex):
"<span>Your page is #Config.PageColour and you have page size of #Config.PageSize</span>"
MessageController.cs
public ActionResult ShowMessage()
{
var htmlToDisplay = _messageDAL.getHtmlMessage();
var messageVm = new MessageVm
{
DisplayMessage = htmlToDisplay;
};
return View("Index.cshtml", "", messageVm);
}
Index.cshtml
<html>
#Html.Raw(#model.DisplayMessage)
</html>
Results
When I run this the rendered page looks like this:
Your page is #Config.PageColour and you have page size of #Config.PageSize
But I want it to interpret the value of the Razor variable with the html block and should look like this:
Your page is Blue and you have page size of A4
Really stuck on this so any help would be appreciated!
Use this line. I hope this may help.
#Html.Raw(System.Web.HttpUtility.HtmlDecode(#model.DisplayMessage))
EDIT 1
You can use any Razor Compiler like the one mentioned below
RazorEngine:
string result = RazorEngine.Razor.Parse(#model.DisplayMessage, new { Name = "Name" });
RazorEngine does not support any of the Mvc helpers such as Html and Url. Since these libraries are supposed to exist outside of Mvc and thus require more work to get them to work with those helpers.**
EDIT 2
You can use a Razor compiler that allows you to use HTML templates called RazorEngine which can be found at https://github.com/Antaris/RazorEngine
From Visual Studio, using the Package Manager Console command:
Install-Package RazorEngine
After installation I changed my controller as follows:
MessageController.cs
public ActionResult ShowMessage()
{
var htmlTemplate = _messageDAL.getHtmlMessage();
var htmlToDisplay = Engine.Razor.RunCompile(htmlTemplate , "messageTemplateKey", null, new { Name = "some model data" });
var messageVm = new MessageVm
{
DisplayMessage = htmlToDisplay;
};
return View("Index.cshtml", "", messageVm);
}
You can use a Razor compiler that allows you to use HTML templates called RazorEngine which can be found at https://github.com/Antaris/RazorEngine
From Visual Studio, using the Package Manager Console command:
Install-Package RazorEngine
After installation I changed my controller as follows:
MessageController.cs
public ActionResult ShowMessage()
{
var htmlTemplate = _messageDAL.getHtmlMessage();
var htmlToDisplay = Engine.Razor.RunCompile(htmlTemplate , "messageTemplateKey", null, new { Name = "some model data" });
var messageVm = new MessageVm
{
DisplayMessage = htmlToDisplay;
};
return View("Index.cshtml", "", messageVm);
}
And it worked first time. Big thanks to #Mukesh Kumar who provided the vital clues to rewrite the code which I've posted as a complete and working answer here.

How to display html action as string in mvc 3 razor view

I am using #Html.Action to call contoller action to return a string. I want to save the string to a variable inside razor as it is comma-seperated.
#Html.Action("GetCategories", new { SP = #ViewBag.Name, SD = "Cad" }).ToString();
//#String s = save above string in here
//#string[] arrS = s.Split(',');
#String test = #Html.Action(......) //tried this but does NOT work.
Public ActionResult GetCategories(string SP, string SD)
{
//Code missing
return Content(return "sugar");
}
How can I save the Html.Action returned data to a string ?
This works for me, just tried in a local MVC project:
#{
string test;
test = #Url.Action("actionName");
}
Url.Action only/always returns a Url. Not sure how this selected answer solved the problem for you unless you DID want the Url (e.g. /Controller/Action/...).
Seems Html.Action was what you wanted all along. It would return the contents "sugar" if you simply had your return coded like this;
return Content("sugar");
You can display it right on the page or use the suggested syntax from "Mark" to save it to a varible

MVC View - JSON not parsing correctly from controller

I am unable to understand why my JSON is not parsing correctly. I am parsing a c# dictionary to a JSON string in my controller. The output is correct there. When I pass the string back to my partial view, it does not render properly, and I am getting "Unexpected Token &" Ive tried it multilple ways in returning it to the view, but to no avail.
View:
var data = #Model.JSONDict
//data output - var data = {"3/1/2014":2,"2/28/2014":1,"2/27/2014":1,"2/26/2014":0,"2/25/2014":0,"2/24/2014":0,"2/23/2014":0}
//var keys = Object.keys(data);
Controller:
string output = JsonConvert.SerializeObject(dict);
//Resulting Output = "{\"3/1/2014\":2,\"2/28/2014\":1,\"2/27/2014\":1,\"2/26/2014\":0,\"2/25/2014\":0,\"2/24/2014\":0,\"2/23/2014\":0}"
ViewData["allEntries"] = output;
model.JSONDict = output;
return PartialView("_Graph", model);
I have also tried parsing out the & acocording to this post: Cannot get data in a view after parsing json data from controller in asp.net mvc like so, but getting the same error message:
storejson= getJSonObject("#ViewBag.JsonData");
function getJSonObject(value) {
return $.parseJSON(value.replace(/"/ig, '"'));
}
The problem is that in the output the JSON is encoded. In order to deal with this you can use the #Html.Raw() like so :
var data = #Html.Raw(Json.Encode(#Model.JSONDict))
But be advised that using #Html.Raw() may cause some security issues so it must be used with caution.

how to download file from other server using mvc asp.net

How can i download file from other server and save it at my own using mvc asp.net with c#?
I am only able to read your title, nevertheless:
WebClient client = new WebClient();
client.DownloadFile("http://your-address.com/FileToDonwload.ext", "c:\PathToTheFileToCreate");
should do what you wanted.
i'd use the System.Web.Mvc.FilePathResult along the following lines:
// most controller logic ommitted
public ActionResult DownloadFile(int fileID)
{
// in this example fileID would map to a file location in the database
var item = _repository.GetByKey(fileID);
// item.DocType would equal "application/msword" / "image/jpeg" etc, etc;
return File(item.DocumentLocation, item.DocType);
}
[edit] - ooops, just realised that this will only work on same server/domain, but have left for reference

Categories

Resources