I have an ASP.NET MVC4 application that is using jQuery to make some calls to a WebApi controller in the same project.  Passing an ID to the controller, /MyController/123 should display different data when the page is loaded.  The problem is that I don't know how to get that ID passed to jQuery.  It's not a query string parameter per se, so this won't work.  What I want is the "123" from the URL.  Is there a common/standard way to do this short of just chopping up the URL?
            Asked
            
        
        
            Active
            
        
            Viewed 225 times
        
    1
            
            
         
    
    
        Community
        
- 1
- 1
 
    
    
        Stephen Collins
        
- 3,523
- 8
- 40
- 61
- 
                    Given a tweak to the regex, I think http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values will work. – Jeromy French Jan 15 '13 at 20:11
2 Answers
1
            you can either put it in a ViewBag object in the controller, ViewBag.PassedId = Id, and then on the front end use the razor or whatever view engine method to place it into a javascript variable,
<script>
var id = @(ViewBag.PassedId);
</script>
Or you can attach it to a hidden form element and grab the value there. But you would tie an object model to pass from the controller.
 
    
    
        benjamin
        
- 1,087
- 7
- 10
- 
                    1This is exactly what I was looking for! I never thought about intermixing Razor code with Javascript. Thanks! – Stephen Collins Jan 15 '13 at 21:40
0
            
            
        I made an update to one of the answer's in the question Jeromy linked to for one of my projects:
(function ($) {
    //http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values
    //usage $.QueryString["param"]
    $.QueryString = (function (a) {
        if (a == "") return {};
        var b = {};
        for (var i = 0; i < a.length; ++i) {
            var p = a[i].split('=');
            if (p.length != 2) continue;
            b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
        }
        return b;
    })(window.location.search.substr(1).split('&'));
    $.mvcId = (function (a.toLowerCase()) {
        //usage $.mvcId("Bar"); /Foo/Bar/162 (Gets 162)
        var b = location.href.toLowerCase();
        var c;
        if (a != "") {
            a += "/";
            c = b.lastIndexOf(a);
            if (~c) { // ~ = truthy http://stackoverflow.com/questions/1789945/javascript-string-contains
                b = b.substring(c, b.length);
            }
            else {
                throw "didn't match querystring";
            }
        }
        c = b.lastIndexOf("/");
        var id = b.substring(c + 1, b.length);
            return id;
    });
})(jQuery);
so use it as
//url is /foo/bar/123
var foo = $.mvcId("bar");
which returns 123
 
    
    
        Eonasdan
        
- 7,563
- 8
- 55
- 82