2014-02-08 52 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重定向到我们的测试