0

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!

0

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

5 Comments

That's a pretty good idea too.. You could have a server-side helper generate a JSON object and just do one call to one div to pull all your URLs out..
Yep, I use PHP and it's incredibly simple converting an array or object to a JSON string. Then with javascript it's very easy to parse a JSON string into an array.
Do you even need to store it in a DIV though, or could you just store the parsed JSON string (an array) in a javascript variable?
Thanks!, the array sounds like it might work. I can keep a global variable of the array of urls. Atleast, it will clean up my _layout page.
Cool, glad I could help. If you run into any problems with the javascript let me know, but it should be pretty straightforward.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.