0

I have an index view of cards (e.g. playing cards) laid out in a BootStrap grid. Each card is in a div, and I have a jQuery click handler for each div, to open a details page for any card (card div) that is clicked. So the redirect from the index to detail view is all accomplished using this (rather smelly) JavaScript:

var showDetail = function (index) {
    const newUrl = "@($"http://{Model.HostName}{Url.Action("Details", "Card")}/")" + index;
    window.location = newUrl;
};

I don't like to depend on the Razor code nugget to give me the hostname and the url's path. Does JavaScript have any functionality that I can use to achieve the same as the above dodgy code?

7
  • 2
    developer.mozilla.org/en-US/docs/Web/API/URL/URL Commented Nov 9, 2017 at 12:39
  • @gurvinder372 The URL ctor requires a url parameter, and if its value is a relative URL, it also requires a base URL parameter. To provide that base url, I will still need to use $"http://{Model.HostName}, where I don't want any hard coding. How do I adjust for SSL? Commented Nov 9, 2017 at 12:46
  • @Satpal I don't have a care in the world if IE doesn't support it. I don't support IE. Edge supports it though, and IE will probably be deprecated by the time this project is finished. Commented Nov 9, 2017 at 12:49
  • IE will probably be deprecated, Thats the best thing I header today. You can create an anchor on the fly and read its property $('<a>', { "href" : relativeUrl}).prop('href ') Commented Nov 9, 2017 at 12:50
  • 1
    @Satpal Yes, sorry, I misread your first comment about the anchor. Commented Nov 9, 2017 at 12:54

1 Answer 1

2

You can create create an anchor on the fly and read its href property.

console.log($('<a>', {
  "href": '/test/for/relative/url'
}).prop('href'))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

And, Also URL API can be used.

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

3 Comments

Thanks. I really learned something fairly esoteric about jQuery today.
@ProfK, you will get the same result using vanilla js. I was being lazy
Why use vanilla when you have the Swiss chocolate of jQuery?

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.