in asp mvc, can I dynamically generate javascript? - c#

On my aspx view, I would like to generate javascript where some parts are generated:
before generation:
<script type="text/javascript">
var A = 'an id';
var B = "http://www.yahoo.com" + <%= Model.pathname %>;
</script>
After generation:
<script type="text/javascript">
var A = 'an id';
var B = "http://www.yahoo.com/videos/index.htm" ;
</script>
is this possible? what options do I have?

I suggest the following code:
<script type="text/javascript">
var A = 'an id';
var B = "http://www.yahoo.com<%= Model.pathname %>";
</script>
Maybe the IntelliSense is not completely right in Visual Studio, but it will work.

yes, it's entirely possible, javascript is not executed untill way after all of this stuff is rendered, you have pretty much whatever options you can imagine.

Yes this should work fine, just surround the directive with single quotes for example:
<script type="text/javascript">
var A = 'an id';
var B = "http://www.yahoo.com" + '<%= Model.pathname %>';
</script>

Yes, that's possible.
If the JavaScript code is in your view, then simply doing the: <%= Model.pathname %> would work.

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.

I just want to change the URL on Runtime?

I am having anchor tag referring to a url i.e
<a taget='_blank' href='http://localhost:4850/en/abc.xml'>
I just want on runtime after clicking on this hyperlink the website will go to
http://localhost:4850/abc.xml
instead of
http://localhost:4850/en/abc.xml
i.e the "en" from the url is removed.
I am having a .Net Application
Assume that your anchor tag with id is like
<a taget='_blank' id="url" href='http://localhost:4850/en/abc.xml'>
Using javascript, on clicking your anchor tag
$('#url').click(function(e){
e.preventDefault();
window.location.href = 'http://localhost:4850/abc.xml';
});
It will redirect you to respected url.
Try this:-
Your anchor tag is like this:-
<a taget='_blank' href='http://localhost:4850/en/abc.xml' id="anc1">Test</a>
Use this script
<script src="https://code.jquery.com/jquery-1.12.3.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("a[ID$='anc1']").click(function () {
var url = $(this).attr("href");
var newurl = url.replace("/en", "");
$(this).attr("href", newurl);
});
});
</script>

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.

Mix Razor and Javascript code

I'm pretty confused with how to mix razor and js. This is the current function I am stuck with:
<script type="text/javascript">
var data = [];
#foreach (var r in Model.rows)
{
data.push([ #r.UnixTime * 1000, #r.Value ]);
}
If I could declare c# code with <c#></c#> and everything else was JS code -- this would be what I am after:
<script type="text/javascript">
var data = [];
<c#>#foreach (var r in Model.rows) {</c#>
data.push([ <c#>#r.UnixTime</c#> * 1000, <c#>#r.Value</c#> ]);
<c#>}</c#>
What is the best method to achieve this?
Use <text>:
<script type="text/javascript">
var data = [];
#foreach (var r in Model.rows)
{
<text>
data.push([ #r.UnixTime * 1000, #r.Value ]);
</text>
}
</script>
Inside a code block (eg, #foreach), you need to mark the markup (or, in this case, Javascript) with #: or the <text> tag.
Inside the markup contexts, you need to surround code with code blocks (#{ ... } or #if, ...)
you also can simply use
<script type="text/javascript">
var data = [];
#foreach (var r in Model.rows)
{
#:data.push([ #r.UnixTime * 1000, #r.Value ]);
}
</script>
note #:
Never ever mix more languages.
<script type="text/javascript">
var data = #Json.Encode(Model); // !!!! export data !!!!
for(var prop in data){
console.log( prop + " "+ data[prop]);
}
In case of problem you can also try
#Html.Raw(Json.Encode(Model));
A non conventional method to separate javascript from the view, but still use razor in it is to make a Scripts.cshtml file and place your mixed javascript/razor there.
Index.cshtml
<div id="Result">
</div>
<button id="btnLoad">Click me</button>
#section scripts
{
#Html.Partial("Scripts")
}
Scripts.cshtml
<script type="text/javascript">
var url = "#Url.Action("Index", "Home")";
$(document).ready(function() {
$("#btnLoad").click(function() {
$.ajax({
type: "POST",
url: url ,
data: {someParameter: "some value"},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#Result").text(msg.d);
}
});
});
});
</script>
This is my way to hack Razor and use Javascript without freaking out Intellisense.
Obviously you should use <text> but with an "expedient": double braces before.
This is what happens if a single brace is used:
This is what happen if a couple of braces are used:
Now constants and variable have been recognized.
It's better, but not good!
There is still the "less than" symbol that confuses intellisense making it think that following is the name of a tag. The "less than" sign is signaled as error and from here there are parsing errors as "console.log" shows.
You need to add something that quiets intellisense and doesn't get returned in the final JS code at compile time.
Solution: use this comment after "less than": /*>*/
This is the result
It's quite strange to see, but it works as it should.
you can use the <text> tag for both cshtml code with javascript
Wrap your Razor code in #{ } when inside JS script and be aware of using just #
Sometimes it doesn't work:
function hideSurveyReminder() {
#Session["_isSurveyPassed"] = true;
}
This will produce
function hideSurveyReminder() {
False = true;
}
in browser =(

Categories

Resources