How does a jquery script file get the Asp.Net MVC 3 route id value?

URL http://localhost:52974/App/Detail/23432 . I know that the following code can get ID (23432), and it can be used in javascript code embedded in the cshtml file.

 @ViewContext.RouteData.Values["id"] 

However, I have an external jQuery script file that processes the document.ready function. The following approach will not work, because it is not a cshtml file. What is 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"]; 
+8
jquery asp.net-mvc-3
source share
3 answers

I would get a view to output a script tag that will call the init function call in external js, passing id as a parameter.

View:

 <script> app.init('@ViewContext.RouteData.Values["id"]'); </script> 

external js:

 var app = {}; (function(app){ var _id; app.init = function(id){ _id = id; } })(app); 
+11
source share

You can save the value in a hidden input field in your 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 will also have access to the ID from an external script :)

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

All Articles