Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How jquery script file gets the ID value of Asp.Net MVC 3's route data?

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"];
like image 334
ca9163d9 Avatar asked Jul 11 '11 22:07

ca9163d9


1 Answers

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);
like image 146
redsquare Avatar answered Nov 10 '22 04:11

redsquare