释放后ajax无法正常工作

时间:2014-02-08 19:51:22

标签: jquery asp.net-mvc-3

以下是我的代码,它在Visual Studio中有效,但在我将它发布到我们的测试环境时无效。

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;
    }

它进入错误处理程序并显示警告消息未找到我在测试环境中调试了它有staus 404

2 个答案:

答案 0 :(得分:0)

我建议您使用@Url.Action(....

  

It生成操作方法的完全限定URL。

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

如果您的代码位于razor视图中而不是js文件中,则此方法有效。如果您在js文件中调用函数。您可以将网址从function代码

传递到razor

答案 1 :(得分:0)

问题解决了:当我在我的JS中将网址更改为“../Country/GetCitiesByCountryId”时,它工作正常。

我认为它在我们的测试环境中不起作用,因为测试环境是一个虚拟目录,我们使用url重定向来进行测试