I have a javascript file that I am including to a ASP.NET MVC view dynamically. This script sets some javascript variables whose values I would like to get from and HTML helper.
The following sets the js variables equal to the string containing the ‘<%’. How should this be formatted so that the server tags are evaluated when this file is included?
Thanks!
var testPortal = ns.TestPortal;
testPortal.context = {};
testPortal.context.currentUserId = "<%= Html.GetCurrentUserId() %>";
testPortal.context.currentHwid = "<%=Model.Hwid %>";
testPortal.context.currentApplicationId = "<%= Html.GetCurrentApplicationId(Model.ProductName) %>";
Update
I am attempting to implement the solution provided to me by Darin below. The new action is working (tested it directly by typing url). However the when I try to create the script tag with a contentPlaceHolder on my view the action is never called. The script tag is never added to the view.
Can someone tell me why this might be??
<asp:Content ID="Content3" ContentPlaceHolderID="DynamicIncludes" runat="server">
<script type="text/javascript" src="<%= Url.Action("Index","Context", new{applicationName = Model.ProductName, hwid = Model.Hwid}) %>">
alert("helloo");
</script>
</asp:Content>
Why is the above script not being added?
You cannot use server side includes such as
<% %>inside static.jsfiles and that’s because they are not processed by ASP.NET. What you could do instead is to define a controller action or a custom Http handler which will set the responseContent-TypeHTTP Header totext/javascriptwhich could serve dynamic content. For example:For example:
and inside
MyDynamicJs.aspxyou could use server side tags:Now all that’s left is to include this controller action somwhere: