alpha
alpha

Reputation: 501

better way of passing URL string to javascript file?

I am using the following in my _layout.cshtml

<div id="authorLoader" data-request-url="@Url.Action("Index", "Author", new { area = "Book" })"></div>

In js file, I retrieve the url as so:

var url= $('#authorLoader').data('request-url');

Works fine, however, I end up having 20+ div tags in my layout page. Is there a better way to pass url strings to javascript? Or is this recommended way?

Thanks!

Upvotes: 0

Views: 1334

Answers (2)

XeroxDucati
XeroxDucati

Reputation: 5190

This is a decent way to do it.. I sometimes 'cheat' and drop in some JS right into my template, and do something like

<script>
    var url = "@Url.Action("Index", "Author", new { area = "Book" })";
</script>

Its not much cleaner, but at least it saves a jquery operation.

Upvotes: 2

Gavin
Gavin

Reputation: 7944

Not sure of the context of this request, but could you construct a javascript array of URLs and then pass the array to the function that reads them? Or alternatively construct a JSON string. Depends on how you plan to use it.

Upvotes: 1

Related Questions