The URL is http://localhost:52974/App/Detail/23432
. I know the following code can get the ID (23432) and it can be used in javascript code embedded in a cshtml file.
@ViewContext.RouteData.Values["id"]
However, I have an external jQuery script file which handle document.ready function. The following approach will not work because it's not a cshtml file. What's the best approach to get the MVC route ID value besides using javascript to parse the URL?
$(document).ready(function () {
var id = @ViewContext.RouteData.Values["id"];
I would get the view to render out a script tag that would invoke a call to an init function in the external js passing the id as a param.
view:
<script>
app.init('@ViewContext.RouteData.Values["id"]');
</script>
external js:
var app = {};
(function(app){
var _id;
app.init = function(id){
_id = id;
}
})(app);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With