c# - Render javascript server side -
i want create pretty simple script on server (a client proxy server side events). whats common way of render scripts server side using mvc4?
update after first answer: want include example @scripts.render("~/eventaggregation/events")
, should invoke code on server generates javascript c# code, for lib cant razor page or mvccontroller, want close signalr's hub proxy, looked @ code several hundred lines of codes injecting dynamic generated script, must easier that?
since stated cannot use mvccontroller or razor view, closer metal: ihttphandler
.
so start writing one:
public class myhandler : ihttphandler { public void processrequest(httpcontext context) { var response = context.response; response.contenttype = "text/javascript"; var message = "this super dynamic message. utc time is: " + datetime.utcnow.tolongtimestring(); var js = string.format("alert({0});", new javascriptserializer().serialize(message)); response.write(js); } public bool isreusable { { return true; } } }
then write corresponding route handler:
public class myhandlerprovider: iroutehandler { public ihttphandler gethttphandler(requestcontext requestcontext) { return new myhandler(); } }
and in application_start
add route:
protected void application_start() { routetable.routes.add( new route( "eventaggregation/events", new myhandlerprovider() ) ); }
and if didn't want manually having add route in application_start
use webactivator
. write static startup class:
internal static class startup { public static void application_start() { routetable.routes.add( new route( "eventaggregation/events", new myhandlerprovider() ) ); } }
and use assembly wide attribute:
[assembly: webactivatorex.preapplicationstartmethod(typeof(mvcapplication1.startup), "application_start")]
and that's left in view reference it:
<script type="text/javascript" src="~/eventaggregation/events"></script>
Comments
Post a Comment