7

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"];

3 Answers 3

10

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);
Sign up to request clarification or add additional context in comments.

Comments

7

You could store the value in a hidden input field in you view;

<input type="hidden" value='@ViewContext.RouteData.Values["id"]' id="routeDataId />

and then in your jQuery script;

$(document).ready(function() {
    var id = $('#routeDataId').val();

    // The rest of your script
});

Then you'll have access to the ID from your external script too :)

Comments

0
var id = @HttpContext.Current.Request.RequestContext.RouteData.Values["ID"].ToString();

Comments

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.