How do I add Asp.Net Server tags to JS and have them evaluated?
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 .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>
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?
精彩评论