I am working on a legacy application and I want to move some JS code onto a separate JS file.
I will have to refractor some of the code to do this. I can put #Url.Content statements into data attributes in the HTML.
But how would I replace this line of code?
var array = #Html.Raw(Json.Encode(ViewBag.JobList));
A separate JS file will not know what #Html.Raw means.
Server side code like that cannot run in a seperate javascript file. My solution for such problems is having a short javascript part in the head that runs on the onload event. There you can set variables that you can use in a seperate javascript file:
in the head:
array = #Html.Raw(Json.Encode(ViewBag.JobList));
in the seperate javascript file:
var array;
Then, in the seperate javascript file you can do with your array whatever is necessary.
The ViewBag.JobList data is only known at HTML page generation time. To include it in an external JavaScript file, you have to have another ASP.NET resource that recalculated ViewBag.JobList and then served as part of a dynamic JavaScript file. This is pretty inefficient.
Instead, do what you're doing with the URLs: pass the data through the DOM. If you're writing into normal DOM instead of a script block, you don't need the raw-output any more (*), normal HTML escaping is fine:
<script
id="do_stuff_script" src="do_stuff.js"
data-array="#Json.Encode(ViewBag.JobList)"
></script>
...
var array = $('#do_stuff_script').data('array');
// jQuery hack - equivalent to JSON.parse($('#do_stuff_script').attr('data-array'));
(Actually, the raw-output might have been a security bug, depending on what JSON encoder you're using and whether it chooses to escape </script to \u003C/script. Writing to HTML, with well-understood HTML-encoding requirements, is a good idea as it avoids problems like this too.)
I think you need to create action with JavaScriptResult
public ActionResult Test()
{
string script = "var textboxvalue=$('#name').val();";
return JavaScript(script);
}
But, before proceeding please go through following links
Beware of ASP.NET MVC JavaScriptResult
Working example for JavaScriptResult in asp.net mvc
I would also follow MelanciaUK's suggestion :
In your javascript file, put your code inside a function :
function MyViewRefactored( array ){
... your code ...
}
In your view, leave a minimal javascript bloc :
<script>
var array = #Html.Raw(Json.Encode(ViewBag.JobList));
MyViewRefactored( array );
</script>
Related
Heres my code but removed some changed code to something smaller!
Javascript code:
// /JS
function callme() {
var test = 1
alert(test);
}
Pug code:
// /first.pug
var funct = require('../JS');
button(onclick='clickme()') click
script.
function clickme() {¨
// trying to call callme function from my javascript file but i really dont know how.
callme();
}
Sorry about this question i dont use pug but this was already made with pug so i cannot go changing it since it has alot more code but didnt post all not needed code here.
Pug has no capability to directly run JavaScript. It is used to generate HTML.
You are already generating HTML with embedded client-side JavaScript.
You need to write the HTML to include the external JavaScript.
i.e. <script src="/url/to/JS.js"></script>
In Pug that would be:
script(src="/url/to/JS.js")
Make sure your HTTP server gives the JS a public URL!
I'm try to add a value to my vb variable in my js code, this is my example
<script>
'<%Dim Myvariable As Integer%>' = 201278
</script>
but this doesn't work.
Is there a way to do this?
Declare variable either protected or public:
Protected test As Integer = 201278;
And in .aspx file:
<script>
<%=test.toString()%>
</script>
edit.
that comment doesn't make any sense #JoséGregorioCalderón the example shows that it IS in script tags. If you mean the file is an external JS file, that is a different problem.
You could solve this in two ways.
1) You serve the JS file as an ASPX file to generate parts of it that are dynamic. you'll need to take care of the headers to serve it is text/javascript
2) You write the variable to your HTML as a data attribute and read it into your JS directly.
i.e.
or...very quick pseudo code.
<body id="myBody" data-variable="<%=MyVariable%>">
var bodyElement = document.getElementById('myBody')
alert(bodyElement.dataset.variable);
I am trying to write razor code inside javascript where I am trying to use a local variable inside the razor code. Here is the sample code:
<script type="text/javascript">
for (i = 0; i < data.result.length; i++) {
$("#member-table tbody").append("<tr>");
var id = data.result[i].MemberId;
var actions = $("<td>" + #Html.ActionLink("Detay", "Edit", new { id }) + "</td>)");
}
</script>
the problem is that id is not recognized by the razor code (i.e. it does not exist in the current context). How can I achieve that ? Is there any way ?
It's not possible to access a javascript variable in a razor block.
That's because razor is executed in the server, and javascript is executed in the browser.
However, by looking at your code it seems like you are using javascript to populate a table and that's bad, there are two patterns for solving this problem, one that solves everything in the server, and another one that solves everything in the browser.
Solving everything in the server:
If you decide that you want to solve everything in the server, your javascript should request the contents from the server and load them into a placeholder without changing them, something like:
$("#myButton").click(function(){
$("#myDinamicDiv").load("/Path/ToView");
});
and then you use razor's foreach loop to generate the table's html:
#foreach (var x in ViewBag.MyData)
{
<tr>
<td>Generate contents here, including links </td>
</tr>
}
Solving everything in the client:
As pointed out in another answer, if you are using the default routing, you can just create direct strings in the javascript code and add them to your page, keep in mind however, that when using this solution, as your page gets complex, your javascript will became less and less maintainable, having a for loop that iterates over data is a sign that maybe you can benefit from javascript UI frameworks like Angular.js and Knockout.js, in fact, what you are doing is the core of Knockout.js's third lesson in its tutorial (Single page applications)
If you're just using default routing, then simply just don't bother with the Razor #Html.ActionLink. Stick with an explicit tag:
var actions = $('<td>Detay</td>');
...obviously with whatever your current controller name is substituted for [your-controller-here].
(And I'm assuming your 'id' isn't necessarily URL-encoded, hence the 'escape'.)
You are mixing server side and client side here. You cannot create #Html.ActioLink using client side variables. Html.ActionLink is rendered on the server, it does not have any clue at all about your client side variables.
If you want to use a client side variable, like "id", render a plain html link (a) tag.
This worked for me once
if ('#ViewBag.DownloadLink' != '') {
window.location.href = '#ViewBag.DownloadLink';
}
I know that Jade is for producing HTML instead of JavaScript, but for a project I'm working, it would be great, and a huge time saver, if I could do this without adding a pipe in every line:
| (function(){
| //Some JavaScript Code
| var foo="#{bar}";
| console.log("This a JavaScript file generated with Jade");
| })()
The idea is to use the output of this template as the source of a regular JavaScript include like this:
<script type="application/javascript" src="foo.generated.js"></script>
So doing something like this:
script(type="application/javascript").
(function(){
//Some JavaScript Code
var foo="#{bar}";
console.log("This a JavaScript file generated with Jade");
})()
won't solve my issue, because I need to output pure JavaScript with no DOM container element.
Is there another way to do this without adding pipes to every line? Or I have to assume that Jade was designed to produce only HTML, give up, and find other solution without Jade?
Thanks in advance!
Produce all XML, include HTML. And jade was not designed to cast large blocks of javascript. The best thing you can do is create a method for obtaining these large blocks, and modifying variables. As it is doing in Example.
I think you should use:
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Content-Type', 'text/javascript; charset=utf-8');
res.end(`(function(){
//Some JavaScript Code
var foo="${bar}";
console.log("This a JavaScript file generated with Jade");
})()`);
I'm using restclient and nokogiri to parse some html which works great, but there is one piece of information stored in a js (jquery) variable which I need to return and I'm not sure how to parse it. I can use Nokogiri to parse the javascript block, but I need one subset of it which is probably simple but I'm not sure how to do it. I could probably regex it but I'm assuming there's an easier way to just ask for it using JS.
#resource = RestClient.get 'http://example.com'
doc = Nokogiri::HTML(#resource)
doc.css('script').each do |script|
puts script.content
end
What I'm trying to get:
<script type="text/javascript">
$(function(){
//this is it
$.Somenamespace.theCurrency = 'EUR';
//a lot more stuff
not sure if that fits, but you could retrieve it as follows:
irb(main):017:0>
string
=> "<script type=\"text/javascript\"> $(function(){$.Somenamespace.theCurrency = \"EUR\"}); "
irb(main):018:0>
string.scan(/\$\.Somenamespace\.(.*)}\);/)
=> [["theCurrency = \"EUR\""]]
Nokogiri is an XML and HTML parser. It doesn't parse the CDATA or text content of nodes, but it can give you the content, letting you use string parsing or regex to get at the data you want.
In the case of Javascript, if it's embedded in the page then you can get the text of the parent node. Often that is simple:
js = doc.at('script').text
if there is the usual <script> tag in the <head> block of the page. If there are multiple script tags you have to extend the accessor to retrieve the right node, then process away.
It gets more exciting when the scripts are loaded dynamically, but you can still get the data by parsing the URL from the script's src parameter, then retrieving it, and processing away again.
Sometimes Javascript is embedded in the links of other tags, but it's just another spin on the previous two methods to get the script and process it.