2014-02-08 54 views
0

以下是我在Visual Studio中工作的代碼,但在將其發佈到我們的測試環境時無法工作。ajax在發佈後不工作

myview.cshtml

@Html.DropDownListFor(m => m.CountryId, 
     new SelectList(Model.Countries, "CountryId", "CountryName"), 
     " -- please choose a country-- ", 
     new { onchange = "CountryDDLChanged()", @class = "form-control" }) 

的JavaScript

function CountryDDLChanged() { 

var url = '@Url.Content("~/Country/GetCitiesByCountryId")'; 
var countryid = $("#CountryId").val(); 
var ddlTarget = $("#CityId"); 

$(ddlTarget).empty(); 

$.ajax({ 
    type: "GET", 
    url: "/Country/GetCitiesByCountryId", 
    data: { countryId: countryid }, 
    success: function (result) { 
     ddlTarget.append("<option value=''> -- please choose a city -- </option>"); 

     $.each(result, function (index, city) { 
      ddlTarget.append("<option value='" + city.CityId + "'>" + city.CityName+ "</option>"); 
     }); 

     $("#cityDiv").show('slow'); 
    }, 
    error: function (req, status, error) { 
     alert(error); 
    } 
}); 
} 

MyController.cs

[AllowAnonymous] 
public JsonResult GetCitiesByCountryId(int countryId) 
    { 
     JsonResult result = new JsonResult(); 
     using (var db = new PetaPoco.Database("myconnection")) 
     { 
      List<City> cities = db.Fetch<City>("Select * from City where CountryId = @0", countryId); 
      result.Data = cities; 
      result.JsonRequestBehavior = JsonRequestBehavior.AllowGet; 
     } 
     return result; 
    } 

它去到錯誤處理程序並顯示警告信息沒有找到我調試JavaScript的測試環境有居留制404

+1

你創造你的JS'url'變量,但沒有不要在'$ .ajax'調用中使用它。那是故意的嗎? – jwatts1980

+0

我沒有使用它,因爲當我使用它時,我的Dev(VS)上的測試環境出現同樣的錯誤。我將它改爲我使用的那個,然後在VS中工作。 – user217648

+0

問題解決:它的工作原理當我在我的JS – user217648

回答

0

我建議你使用@Url.Action(....

它會產生一個完全合格的URL的操作方法。

@Url.Action("GetCitiesByCountryId","Country") 

這工作,如果你的代碼是在Razor視圖,而不是在js文件。如果您在js文件中調用功能。您可以通過網址functionrazor代碼

+0

中將url更改爲'../Country/GetCitiesByCountryId'謝謝Nitin,我已經測試過了,它沒有工作。我認爲它在我們的測試環境中不起作用,因爲測試環境是一個虛擬目錄,並且我們使用了url重定向來進行我們的測試 – user217648

0

問題解決了:它的工作原理當我在我的JS中將URL更改爲'../Country/GetCitiesByCountryId'。

我想是因爲測試環境是它並沒有在我們的測試環境中工作,是一個虛擬目錄,然後我們使用URL重定向到我們的測試