JSON string getting escaped - c#

I am sending a string from JSON ASP.NET MVC, in my view I receive the JSON string and I assign a Script using ViewBag.string.
My problem is in the view, the string type values ​​are replacing the quotes with me & quot; which is causing me errors.
Controller:
var jss = new JavaScriptSerializer();
string retorno = jss.Serialize(chart.ToList());
ViewBag.datos = retorno;
ViewL
<script type="text/javascript">
new Morris.Bar({
element: 'BarChart',
data:#ViewBag.datos,
xkey: 'Planta',
ykeys: 'Cantidad',
labels: 'Mes'
})
</script>
This is the code that generates me to run the view
<script type="text/javascript">
new Morris.Bar({
element: 'BarChart',
data:`[{"Planta":"CO","Mes":3,"Cantidad":2},{"Planta":"EP","Mes":1,"Cantidad":1},{"Planta":"R1","Mes":1,"Cantidad":2},{"Planta":"RM","Mes":3,"Cantidad":3},{"Planta":"RQ","Mes":3,"Cantidad":1},{"Planta":"TY","Mes":1,"Cantidad":1},{"Planta":"TY","Mes":3,"Cantidad":3},{"Planta":"TY","Mes":4,"Cantidad":2},{"Planta":"ZB","Mes":3,"Cantidad":1},{"Planta":"ZB","Mes":4,"Cantidad":1}],`
xkey: 'Planta',
ykeys: 'Cantidad',
labels: 'Mes'
})
</script>

Razor is assuming the content is HTML and is escaping your JSON. Use Html.Raw to stop this behaviour.
...
data:#Html.Raw(ViewBag.datos)
...

Related

Prevent html encoding when using JsonConvert [duplicate]

I'm trying to write an object as JSON to my Asp.Net MVC View using Razor, like so:
<script type="text/javascript">
var potentialAttendees = #Json.Encode(Model.PotentialAttendees);
</script>
The problem is that in the output the JSON is encoded, and my browser doesn't like it. For example:
<script type="text/javascript">
var potentialAttendees = [{"Name":"Samuel Jack"},];
</script>
How do I get Razor to emit unencoded JSON?
You do:
#Html.Raw(Json.Encode(Model.PotentialAttendees))
In releases earlier than Beta 2 you did it like:
#(new HtmlString(Json.Encode(Model.PotentialAttendees)))
Newtonsoft's JsonConvert.SerializeObject does not behave the same as Json.Encode and doing what #david-k-egghead suggests opens you up to XSS attacks.
Drop this code into a Razor view to see that using Json.Encode is safe, and that Newtonsoft can be made safe in the JavaScript context but is not without some extra work.
<script>
var jsonEncodePotentialAttendees = #Html.Raw(Json.Encode(
new[] { new { Name = "Samuel Jack</script><script>alert('jsonEncodePotentialAttendees failed XSS test')</script>" } }
));
alert('jsonEncodePotentialAttendees passed XSS test: ' + jsonEncodePotentialAttendees[0].Name);
</script>
<script>
var safeNewtonsoftPotentialAttendees = JSON.parse(#Html.Raw(HttpUtility.JavaScriptStringEncode(JsonConvert.SerializeObject(
new[] { new { Name = "Samuel Jack</script><script>alert('safeNewtonsoftPotentialAttendees failed XSS test')</script>" } }), addDoubleQuotes: true)));
alert('safeNewtonsoftPotentialAttendees passed XSS test: ' + safeNewtonsoftPotentialAttendees[0].Name);
</script>
<script>
var unsafeNewtonsoftPotentialAttendees = #Html.Raw(JsonConvert.SerializeObject(
new[] { new { Name = "Samuel Jack</script><script>alert('unsafeNewtonsoftPotentialAttendees failed XSS test')</script>" } }));
alert('unsafeNewtonsoftPotentialAttendees passed XSS test: ' + unsafeNewtonsoftPotentialAttendees[0].Name);
</script>
See also:
Does the output of JsonConvert.SerializeObject need to be encoded in Razor view?
XSS Prevention Rules
Using Newtonsoft
<script type="text/jscript">
var potentialAttendees = #(Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model.PotentialAttendees)))
</script>

AngularJS with Entity Framework Core throws an error

Trying to run AnglarJS on my website just executing simple $scope variable and cannot get it to work and throwing errors (image attached). Seems simple but I tried everything, correct me if I am missing any statement. Using VS Code, Entity Framework Core. Page renders perfect.
Index.cshtml
<head>
#section scripts{
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular-resource.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular-route.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular-animate.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="~/SPA/pController.js"></script>
<script src="~/SPA/app.js"></script>
}
<div ng-app="app" ng-controller="pController">
<p{{ word }} /p>
app.js
var app = angular.module('app', ['ngRoute']);
app.controller('pController', pController);
pController.js
var pController = function($scope){
$scope.data = null;
$scope.word = "hello world";
};
pController.$inject = ['$scope'];
RESULT:
UDPATE
Figured something, system cannot find the app.js file. Pasting all the code in html all works.
SOLVED
After a day spent on this problem, I solved it simply putting all my js Angular logic into /wwwroot/js/... I think somehow my project only read js files from that path. Thank you everyone for help!
Reorder the files in your html as:
<script src="~/SPA/app.js"></script>
<script src="~/SPA/pController.js"></script>
Then do any of those:
app.js:
var app = angular.module('app', ['ngRoute']);
pController:
app.controller('pController', function($scope){
$scope.data = null;
$scope.word = "hello world";
});
Or
In case you are using minification:
Modify your app.js file as:
var app = angular.module('app', ['ngRoute']);
app.controller('pController', ['$scope', pController]);
Then your controller file:
var pController = function($scope){
$scope.data = null;
$scope.word = "hello world";
};
If this still didn't work :), put the whole code in one single js file 'app' and then try and let me know the issue.

Fullcalendar/Fetching JSON feed(Edited)

I have a problem with the events in my fullCalendar object not showing when using ajax to fetch the data from my JSON feed. I believe the JSON format is proper though since the output from JSON.aspx is:
[{"id":1,"title":"TESTTITLE","info":"INFOINFOINFO","start":"2012-08-20T12:00:00","end":"2012-08-20T12:00:00","user":1}]
I used Firebug and it seems like the JSON feed is not getting fetched properly?
When I add the upper JSON-feed directly in the events it displays properly.
(Edit) The JSON response is now working, although the events are still not displayed in fullcalendar.
JSON.aspx
public partial class JSON : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Get events from db and add to list.
DataClassesDataContext db = new DataClassesDataContext();
List<calevent> eventList = db.calevents.ToList();
// Select events and return datetime as sortable XML Schema style.
var events = from ev in eventList
select new
{
id = ev.event_id,
title = ev.title,
info = ev.description,
start = ev.event_start.ToString("s"),
end = ev.event_end.ToString("s"),
user = ev.user_id
};
// Serialize to JSON string.
JavaScriptSerializer jss = new JavaScriptSerializer();
String json = jss.Serialize(events);
Response.Write(json);
Response.End();
}
}
And my Site.master
<link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
<link href='fullcalendar/fullcalendar.css' rel='stylesheet' type='text/css' />
<script src='jquery/jquery-1.7.1.min.js' type='text/javascript'></script>
<script src='fullcalendar/fullcalendar.js' type='text/javascript' ></script>
<script type="text/javascript">
$(document).ready(function () {
$('#fullcal').fullCalendar({
eventClick: function() {
alert('a day has been clicked!');
},
events: 'JSON.aspx'
})
});
</script>
I've been scanning related questions for days but none of them seems to fix mine...
Why are your calls so complicated? Try this for now:
$('#fullcal').fullCalendar({
events: 'JSON.aspx',
eventClick: function (calEvent, jsEvent, view) {
alert('a day has been clicked!');
}
});

MVC .Net 4 Razor Problems using <text> tag

Here is my code:
<text>
<script type="text/javascript">
#foreach (var script in Model.Content.StartupScripts)
{
#script
}
</script>
</text>
#script contains a javascript script, but this gets rendered by razor as:
<script type="text/javascript">
{
{
var instanceId = 'blah';
new RequestQueue(' blah
// etc
So...it looks like the tag is not applying to the #script variable because single quotes are being replaced with '. What am I doing wrong?
Thanks!
Since MVC is automatically encoding all output, you need to force it to display raw text. You can do that with #Html.Raw(script) HTML helper.

Setting default text in WYMEDITOR

I've got a question about using WYMEditor in ASP.NET MVC 3 with jQuery. I'd like to set default text in WYMEditor on my web page. If I'm doing in that way :
<script type="text/javascript">
jQuery(function() {
jQuery(".wymeditor").wymeditor( { html : '<strong>some text</strong>'});
});
There is no problem, and wymeditor shows well-formated text, but is I try it in that way :
<script type="text/javascript">
jQuery(function() {
jQuery(".wymeditor").wymeditor( { html : '#ViewBag.HtmlText'});
});
(HtmlText is variable where I keep : <strong>some text</strong>) the WymEditor shows me not formated text <strong>some text</strong>. I tried HtmlEncoding and etc, but it stil isn't working.
Try like this:
<script type="text/javascript">
jQuery(function() {
var html = #Html.Raw(Json.Encode(ViewBag.HtmlText));
jQuery('.wymeditor').wymeditor({ html: html });
});
</script>
And please get rid of this ViewBag as everytime I see it I get sick. Use view models and strongly typed views.

Categories

Resources