asp.net pass javascript code from database
The Question:
Is there a way that I can pass a JavaScript function in开发者_如何转开发to a page (from a database) to be run?
Background info
I have developed a metadata driven asp.net mvc web site (basically I change data in the db, and the pages get generated on the fly).
Unfortunately I have one page that has some routing requirements (i.e. if you choose option 1, then hide item x)
I could solve this by having a custom page, but it would be nice if I could come up with a more robust solution.
So what I am thinking is that I can attach an onchange event handler (based on a metadata value), and then somehow have some code that is executed based on that onchange event.
You can have server-side code render static javascript yes, but you can't change the javascript when on the client due to a change in requirements; you have to render JS code that's dynamic enough to handle all the interactions you may need to do. By server-side code, that means any code as well as any external resources (ie. database). Though, I'm not sure storing static JS code in the DB is buying you anything more than you could already have by storing the JS in a file, and having JS components smart enough to have these different interactions within that file...
So yes server-side storage can render out static JavaScript, but JS can't change from server-side code dynamically, unless your JS code call a web service on the server side.
Make sense?
Its not really the safest thing to do, but using JavaScript's eval() function, you can pass in whatever you want and have it run.
Another idea is to generate a javascript file on the server (whether by getting it from the database or by some other method), and on the page, add a script tag that calls a handler (ashx file) that renders the javascript file.
On the client, you would have this javascript:
var h = document.getElementsByTagName("head")[0];
var js = document.createElement("script");
js.type = "text/javascript";
js.src = "scriptfilegenerator.ashx";
h.appendChild(js);
And on the server (ashx file) you would have this code:
context.Response.AddHeader("content-disposition", "inline; filename=scriptfile.js");
context.Response.ContentType = "text/javascript";
context.Response.Write("your script here");
精彩评论