views:

112

answers:

3

I think I found something very weird in JQuery and ASP.NET MVC.

As mentioned in this question, I have the following JQuery code:

$(function() {
$("#username").click(function() {
        $.getJSON("ViewRecord/GetSoftwareChoice", {username:'123'},
    function(data) {
        alert(data);
    });
    });
});

ViewRecord is the controller and GetSoftwareChoice is the action method. But the URl generated for this is

http://localhost/ViewRecord/ViewRecord/GetSoftwareChoice?username=123

Pretty amazing, isn't it?

Why this is the case?

This is my route:

        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "Default",                                              // Route name
            "{controller}/{action}/{id}",                           // URL with parameters
            new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
        );
+1  A: 

Try using this as your URL:

 $.getJSON("/ViewRecord/GetSoftwareChoice", // etc

Note the prefixed forward slash.

swilliams
A: 

jQuery doesn't know anything about MVC, controllers, or actions. You're telling it: "here is a relative URL - take the URL of the current page and append the relative URL to it." You probably want to say something like:

var newURL = "http://" + document.domain + "/ViewRecord/GetSoftwareChoice";
Bruce
+3  A: 

without a leading slash, the URL's path is a local path and it's resolved relative to the page's path. just like any other URL that you might put into your HTML.

Javier