Skip to content Skip to sidebar Skip to footer

How Do You Output Raw Javascript In Asp.net

I would like to output raw javascript to an aspx response. Using response.write fails because along with the javascript, it dumps all of the other asp.net stuff in the page, for ex

Solution 1:

Use .ashx Generic Handler. Then you can set context.Response.ContentType = "text/javascript" and just use Response.Write

Solution 2:

I'm not sure that I understand your question, but you can try something like this:

Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "registerSomething", "doSomething = function(){ ... }", true);

Solution 3:

You could also disable the viewstate, etc... and remove everything from the aspx file.

<%@Page ... EnableViewState="false" EnableViewStateMac="false"%>

Include nothing else in the aspx file, no runat=server anything. Then write your javascript in the codebehind using response.write.

Solution 4:

This will be pretty tough using WebForms. The best way I can think of would be to add MVC to your project so you can have more control over the output. (Yes, MVC and WebForms can coexist in the same project).

This way you can still leverage the .aspx syntax (or the even-cooler Razor syntax) to produce a javascript file, without WebForms adding all of its annoying stuff to your output.

Solution 5:

I needed this and this was my solution:

Created a file script.aspx and the content was straight javascript with the header directive of the page. Then in the javascript I was able to insert calls to static methods:

<%@ Page Language="C#" ContentType="text/javascript" %>

function someFunction()
{
    var someVar;

    someVar="<%= MyClass.MyMethod() %>";
}

That returned just pure javascript with the server side insertions as needed:

function someFunction()
{
    var someVar;

    someVar="Some string returned by my method";
}

Post a Comment for "How Do You Output Raw Javascript In Asp.net"