3

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 example:

...
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMTAxODk4MjA3OWRk9jVlI2KaQPiVjEC+P0OPYGV74vKjJQZuwD6OaHhb+U0=" />
...

Is there anyway to simply output raw text to the output without having all of the other asp.net stuff on the page? I am trying to use the page as follows:

<script src="mypage.aspx"></script> 

Where this page contains the javascript this triggers off the aspx page, however chrome doesn't like it for obvious reasons... it expects javascript, but it is getting javascript + markup + .NET injected stuff.

Please no comments on why I am doing this! Working on very specific problem.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Zunandi
  • 164
  • 11

5 Answers5

6

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

Joe
  • 80,724
  • 18
  • 127
  • 145
3

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);
James Johnson
  • 45,496
  • 8
  • 73
  • 110
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.

aepheus
  • 7,827
  • 7
  • 36
  • 51
  • I agree with Joey above: ASHX is the most common/accepted way to do what you want. However, if you are for some reason required to do it within an ASPX page, this answer (from aepheus) should help. – mikemanne Aug 22 '11 at 21:44
1

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";
}
Nelson Rodriguez
  • 492
  • 3
  • 12
1

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.

StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315