开发者

Embed javascript Variable within ASP.NET MVC 2 tag

I have a Javascript statement in an MVC view that looks like this and works:

win.attachURL('<%: Url.Action("GraphDetails", "Dashboard", new { area = "Anglian", OSName = "Hello" }) %>');

When I try to extract the variable 'Hello' and put it into a javascript variable (id) and subsequently embed it into my tag like this, it breaks:

var id = "Hello";
win.attachURL('<%: Url.Action("GraphDetails", "Dashboard", new { area = "Anglian", OSName = "' + id + '" }) %>');

Question is, how do I embed a JS variable inside an ASP server tag, that itself is already embedded within Javascript? This is for a local prototype, security concerns are not 开发者_StackOverflow中文版an issue.

Thank you,

Tom.


One is server-side, the other is client-side, you can't mix the two.

When you do it on the server side with the id as a variable it will break because id doesn't exist in the server side context.

Why don't u try break up the statement on the client side?

var id = "Hello";
var actionInit = "<%: Url.Action("GraphDetails", "Dashboard", new { area = "Anglian"}) %>";
win.attachURL(actionInit + "?OSName=" + id");

Note: when appending ?OSName, this may cause some issue if your route doesn't map 100% correctly. eg. u get /Dashboard/GraphDetails?area="Anglian" and u append another "?" that will be an invalid URL. On the other hand, it will also be invalid if your route matches 100% and you append "&OSName". So just check that out first


I don't think you can in general. In this case at least the <%: ... %> part is evaluated at page load time and will never run again.

Instead, you can compute this in JavaScript, e.g.

var id = "Hello";
var baseURL = '<%: Url.Action("GraphDetails", "Dashboard",
                              new { area = "Anglian" }) %>';
win.attachURL(baseURL + '&OSName=' + id);

However that makes assumptions about how you're assembling your routing parameters for that route. You could use Url.Action to generate the full route with a dummy value and then substitute, e.g.

var id = "Hello";
var baseURL = '<%: Url.Action("GraphDetails", "Dashboard",
                              new { area = "Anglian", OSName="ZZZ" }) %>';
win.attachURL(baseURL.replace('ZZZ', id);

but then there's a subtle chance this could go wrong, particularly if you're feeding user generated string into other parameters in the string where they could hit on the value you substitute.

If you really did want to run Url.Action again you'd have to make an AJAX call back to a known URL with the parameters to get the URL, which is overkill really.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜