Methods for dynamically building JavaScript within an ASPX page? - c#

I have a page that is referenced via a <script> tag from a page on another site. In the script src, I pass in the form I want my script to build (from a db table), and the div where the dynamically built form should go. The calling page looks something like this:
<div id="FormContainer"></div>
<script type="text/JavaScript" src="http://www.example.com/GenerateForm.aspx?FormId=1&div=FormContainer"></script>
GenerateForm.aspx contains the code that reads the QueryString parameters for the FormId, and the Div Id, and outputs JavaScript that will build the form.
My question is this. What are the different methods for "outputting" the JavaScript? Some of the JavaScript is static, and can be packaged into an external .js file and I have jQuery too. But should I add that on the GenerateForm.aspx markup page? Or should I use a ScriptManager?
And what about the dynamically built JavaScript? Currently I'm just using Response.Write() for a proof of concept, but instead, should I be doing something else? Use a Literal control on the page and set its value? Use a ScriptManager? Something else?
I know this is a verbose question, so thanks in advance!

If you want to use a seperate, referenced Javascript file, you probably want to do is use an ashx file. Basically this is just a generic handler that you'll use to write directly to the output stream without having to deal with the ASP.NET page lifecycle. If you add a basic Generic Handler (.ashx) to your site from the Add New Item dialog, the template should be enough direction, using context.Response.Write() to output your Javascript dynamically.
The ScriptManager is more useful if you want to output individual lines of Javascript to be ran at certain times, like after an event has fired. Then you can do ScriptManager.RegisterClientBlock(this, this.GetType(), "CodeBlock", "alert('Button clicked');", true); to show a client alert box after a button has been clicked, for example.
Static files should be handled just that way - statically. The server can handle the caching, and does not cause unnecessary processing if you reference the static script file directly from the script tag. However, if you need to load a static script dynamically, you could, for example, create a literal that had the <script> tag inside it. This way it uses the browser's cached version of the static file.

Related

Having trouble using razor C# with JavaScript

I am trying to get Razor (C#) and javascript to play nicely together but I can't seem to do it. I have searched the other articles on StackOverflow, but none of them seem
to work for me.
Some noticeable differences from other posts and mine include the following:
I am using an external JavaScript file (not mandatory, but it is there).
I am using a cshtml file for the header layout for all pages (which puts the head tag in a different file than the one actually attempting to call the function.
I also use jQuery, if it would be easier that way.
What I am trying to accomplish:
All I need to do is get the contents of a tag (innerHTML, or .html in jQuery) (by id, class, whatever) and assign that value to "AppState["gEntryID"] for use with the next page.
Some things I have tried:
function entryClickHandler()
{
#AppState["gEntryID"] = document.getElementById("tester").innerHTML;
}
AND
function entryClickHandler()
{
<text>
#AppState["gEntryID"] = document.getElementById("tester").innerHTML;
</text>
}
I have tried these (and a few other variations on these) in both the external file and the head section within the HeaderLayout File.
I understand that C# runs before the page and the JavaScript mostly runs after the page (at least with events such as this).
Any help would be greatly appreciated.
It doesn't work that way. You cannot set variables in the C#/Razor side with JavaScript without using a form post or ajax submit.
Javascript doesn't get access to the page until after Razor has done it's part and rendered and sent the page.

How to pass data from SQL Server to jQuery var [Flot]

I have two columns of data in an Database on MS SQL Server. One is datetime variable and another is an int.
Im trying jQuery and Flot to plot the datetime vs int.
I can programatically get the data from SQL Server using C#. But how do I pass it to the JavaScript File which has the vars for flot?
If you want to call a script in a loaded html document, you can use the Invoke method from the appropriate HtmlDocument or WebBrowser object to call a javascript function within that page, for example:
http://msdn.microsoft.com/en-us/library/system.windows.controls.webbrowser.invokescript.aspx
I am unsure how you would pass the data from c# to a *.js file in your case, I dont think its possible. But you could try a hack on the page that contains the *.js include you could try declaring and setting the javascript variable to the c# code (so in the ASPX, if its ASP.NET) and then putting the *.js include reference after that point and in it not re-declaring the variable but using it. You can also use JSON or AJAX to call server side code and return values and execute code.
Scenario 1: (The hack way, which is not clean and hard to maintain but does the job)
File.aspx
<script language="javascript" type="text/javascript">
var MyVariable = "<%=C_Variable_On_Code_Behind%>";
</script>
<script type="text/javascript" src="/scripts/YourJsFile.js" >
</script>
YourJsFile.js
if(MyVariable != null && MyVariable.length > 0){
//Do some thing.
}
Scenario 2: (JSON, AJAX, JQUERY UI)
jquery ui sample for a autocomplete: try this link
Another example: Or this link
Scenario 3: (Writing to the client from server-side c#)
Use RegisterStartupScript or RegisterClientScriptBlock via the ClientScriptManager object, here is a dummy code I put together so you can look them up and have an idea so you can find out more, this is not meant to be full code.
ClientScriptManager script = Page.ClientScript;
if (!script.IsClientScriptBlockRegistered(this.GetType(), "YourLabelForThis"))
{
script.RegisterClientScriptBlock(this.Page.GetType(), "YourLabelForThis",
"<script type=\"text/javascript\">var MyVariable = "Dummy text";</script>", false);
}
Please note you have to place the js code as an include or further code in the right position in the page whther you want it before or after this code, so lookup RegisterStartupScript or RegisterClientScriptBlock via the ClientScriptManager. To see where your code will be placed and how you should handle it. Also look at the page source in your browser to also see it.

HTML helpers in ASP.NET MVC 3 with Javascsript action

I have many HTML helper in Helpers.cshtml file, but some of the helper (html) need some jquery action, so how do i can call jquery inside helpers.cshtml, is that possible?
i know we can keep the js file in header or particular page, but i do not want to do like that, i want to use jquery or javascript only on the page which loaded particular helper.
anyone have idea on this?
My scenario is, i have list box control, that is properly loading from helper, but i need to apply custom theme to the list box.
Little more Clarity
//in index.cshtml
#Helpers.testListBox("mylist" "1,2,3,4,5,6,7")
//in Helpers.cshtml
#helper testListBox(string listName, string listData){
//...... HTML code .........
//Javascript here?
}
With Web Forms, the framework could automatically include Javascript (once) when certain server controls were used on a page; ASP.Net MVC has no such facility. It sounds like this is what you're missing.
The way to do it is on the client. Look at RequireJS at http://requirejs.org/. This is a client-side library for managing Javascript dependencies. This does what Web Forms did, but better, and it does more. Your master layout will have a script tag like this:
<script src="/Scripts/require.js" type="text/javascript" data-main="/Scripts/main"></script>
This can be the only script tag you include on every page. Everything else can be dynamically loaded only as needed by RequireJS. It's true that you load this on every page, but it's smaller than jQuery, and it earns its place because it does so much for you.
Using your example, let's say you have this markup:
#Helpers.testListBox("mylist" "1,2,3,4,5,6,7")
and it renders HTML and needs jQuery scripting. You would render this:
// HTML for list box here
<script type="text/javascript>
require(['jquery'], function($) {
// Do your jQuery coding here:
$("myList").doSomething().whatever();
});
</script>
The require function will load jQuery, unless it has already been loaded, and then execute your code. It's true that your jQuery snippet is repeated once per use of the HTML helper, but that's not a big deal; that code should be short.
RequireJS manages dependencies effectively; you can have module A, and module B which dependes on A, and module C which depends on B. When your client code asks for module C, A and B will be loaded along with C, and in the correct order, and only once each. Furthermore, except for the initial load of require.js, scripts are loaded asynchronously, so your page rendering is not delayed by script loading.
When it's time to deploy your site on the web server, there's a tool that will examine the dependencies among the Javascript files and combine them into one or a small number of files, and then minimize them. None of your markup has to change at all. While in development, you can work with lots of small, modular Javascript files for easy debugging, and when you deploy, they are combined and minimized for efficiency.
This is much better than what the web forms framework did, and entirely client-side, which in my opinion is where it belongs.
You can put a <script> tag in the helper body.
How about this for an example of a partial view:
#model Member.CurrentMemberModel
#{
var title = "Test View";
}
<script type="text/javascript">
// Javascript goes in here, you can even add properties using "#" symbol
$(document).ready(function () {
//Do Jquery stuff here
});
</script>
#if (currentMember != null)
{
<div>Hello Member</div>
}
else
{
<div>You are not logged in</div>
}

jQuery with C# doesn't fire onclick event

I have an ASP.NET application that also uses jQuery for modal pop-ups. If I put an ASP button (or image button) within the DIV for the jQuery modal, the "OnClick" event does not fire.
How can I fix this?
When you create the dialog, you need to move it a bit for ASP.Net, like this:
$(".class").dialog({
//options
}).parent().appendTo("form");
By default the .dialog() moves the content to just before </body> which most importantly is outside the <form></form>, so elements within it won't be included in the POST (or GET) to the server. If you manually move it like I have above, it'll resolve this issue.
By default, jQuery places the modal OUTSIDE of the asp.net <form> element.
You can easily append it to the form like:
$("#your-modal").parent().appendTo("form:first");
And this should fix your problems. It's a common problem with jQuery/ASP.NET.
Enjoy

Difference between Response.Write() and ClientScript.RegisterStartupScript()?

What is the difference between Response.Write() and ClientScript.RegisterStartupScript()
Thank you.
The Response.Write method can be used to output code during the rendering phase of the page. The <%= %> server tag is a shortcut for <%Response.Write( )%>.
If you use Response.Write from the code behind, you will write to the page before it has started rendering, so the code will end up outside the html document. Eventhough the browser will execute the code, it doesn't work properly. Having something before the doctype tag will make the browser ignore the doctype and render the page in quirks mode, which usually breaks the layout. Also, as the script runs before anything of the page exists, the code can't access any elements in the page.
The ClientScript.RegisterStartupScript method is the preferred way of adding script dynamically to the page. It will render the script at the end of the form so that it doesn't break the html documnet, and it can access the elements in the form.
Also, you give each script an identity, which means that duplicates are removed. If a user control registers a script, and you use several instances of the user control, the script will only be rendered once in the page.
There is a huge difference.
Basically Response.Write will write to your response stream right now, normally this will put whatever you write at the very top of your page output, even before the tag (unless you call it after the page render event).
When you use RegisterStartupScript it will wait and write your JavaScript to the response stream after the page's controls have rendered (IE, the controls wrote their HTML to the response stream). This means the JavaScript you register will be executed by the browser after the other HTML before it has been loaded into the DOM. This is very similar to the event. Another thing this does is if “registers” the script so if you have more than one control on the page that both need that JavaScript they can check to see if it’s already been registered so it’s only rendered once and both controls use it client side.
Hopefully that makes sense, there are more details then that but I tried to keep it simple.
Response.Write
The Write method writes a specified
string to the current HTTP output.
ClientScriptManager.RegisterStartupScript
Registers the startup script with the
Page object.
As I think, both these methods are unrelated. Response.Write() can be used to write something on page that is rendered. While ClientScript.RegisterStartupScript() can be used for registering a javascript on page start up.

Categories

Resources