Search code examples
javascriptjqueryrazorwebmatrix-3

How should I call a cshtml file from javascript/jquery?


I'm trying to add cascading dropdown lists to a page on my site. I've followed the example presented at http://www.mikesdotnetting.com/article/196/webmatrix-jquery-cascading-dropdown-lists The only changes being that I've changed the variable names to suit my app and, as I only want the functionality to exist in certain situations (i.e. creation of a new record), there's an if statement around the relevant code.

Although my 2nd dropdown list is disabled on page load (as expected), it does not become enabled when one of the 1st dropdown list items gets selected.

My suspicion is that I'm not calling GetClients.cshtml (my variation of Mike's GetProducts.cshtml) correctly, probably due to the line:

$.getJSON('/GetClients/' + ActivityID, function (clients) {

not looking in the correct folder.

In an ideal world, I could use the Razor tilde (~) to force a full path that would look correctly regardless of using the server version or localhost. But that doesn't seem to be an option in JavaScript.

GetClients.cshtml is located in the same folder as the cshtml file that contains the JS code, HTML dropdown lists, etc. that I'm trying to control. Could someone let me know whether the code above does or does not reference a file that's 'next door', and if not, to what should I amend the above line of code?


Solution

  • If your GetClients.cshtml file is in a folder below the root, you need to include that folder in the URL that you pass to the getJSON method. For example, let's say your structure is like this:

    root
        folder
            GetClients.cshtml
            CallingPage.cshtml
        Default.cshtml
        etc
    

    The url you pass to the getJSON method should be /folder/getclients plus any additional URLData/querystrings you want to pass.