How Do I Add Asp.net Server Tags To Js And Have Them Evaluated?
Solution 1:
You cannot use server side includes such as <% %>
inside static .js
files 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 response Content-Type
HTTP Header to text/javascript
which could serve dynamic content. For example:
For example:
public ActionResult MyDynamicJs()
{
return View();
}
and inside MyDynamicJs.aspx
you could use server side tags:
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
<% Response.ContentType = "text/javascript"; %>
var testPortal = ns.TestPortal;
testPortal.context = {};
testPortal.context.currentUserId = "<%= Html.GetCurrentUserId() %>";
testPortal.context.currentHwid = "<%=Model.Hwid %>";
testPortal.context.currentApplicationId = "<%= Html.GetCurrentApplicationId(Model.ProductName) %>";
Now all that's left is to include this controller action somwhere:
<script type="text/javascript" src="<%= Url.Action("MyDynamicJs", "SomeController") %>"></script>
Solution 2:
Provided the model is set up correctly and you have not done something really strange with the view, you should be able to populate the javascript in this manner, as it will only be seen as JavaScript when sent to the browser.
What errors or funkiness are you getting from the above code?
Post a Comment for "How Do I Add Asp.net Server Tags To Js And Have Them Evaluated?"