【问题标题】:Ajax call from external JS file in MVC 4来自 MVC 4 中外部 JS 文件的 Ajax 调用
【发布时间】:2017-03-25 09:35:44
【问题描述】:

我正在尝试通过外部 js 文件使用 ajax 检索有关选择国家/地区 ID 的城市数据,并注意我的代码在本地运行。 问题是当我使用内部 jquery 函数时,即在 MVC 视图中,我能够在选择国家时正确加载城市下拉列表,因为当我尝试使用单独的 JS 文件时,城市下拉列表没有被加载。

下面是 Ajax 调用..

$(document).ready(function () {

         $("#Country").change(function () {

             $.ajax({
                 type: 'POST',
                 url: '@Url.Action("GetCities")',
               data: { id: $("#Country").val() },
               success: function (data) {
                   $("#City").empty();
                   $("#City").append('<option value=" ' + 0 + ' ">' + "---Select---" + '</option>')
                   $.each(data, function (i, City) {
                       $("#City").append('<option value="' + City.value + '">' + City.Text + '</option>')
                   });
               }
           });
       })
    });

【问题讨论】:

  • 请帮帮我..
  • @Url.Action 语法仅适用于 .cshtml 文件,外部脚本必须包含已解析的 url,如“/ControllerName/GetCities”,如果部署到子目录,则为“/sbdirectory/ ControllerName/GetCities”。

标签: asp.net-mvc-4 asp.net-ajax


【解决方案1】:

尝试调试代码并检查正确的 url 和参数发布到服务器。

$("#Country").change(function () {

 debugger;
  var dropdnSelectedVal = $(this).val();

     console.log(dropdnSelectedVal);

         $.ajax({
             type: 'POST',
              dataType: "json",
             url: '@Url.Action("GetCities")',//here is the issue, Its can not be parsed in external js file
           data: { id: $("#Country").val() },
           success: function (data) {

            debugger;
            var responseDataFromServer = data;
            console.log(data);
               $("#City").empty();
               $("#City").append('<option value=" ' + 0 + ' ">' + "---Select---" + '</option>')
               $.each(data, function (i, City) {
                   $("#City").append('<option value="' + City.value + '">' + City.Text + '</option>')
               });
           }
       });
   })
});

或者, 只需在浏览器网络选项卡上检查浏览器发布到服务器的参数数据

【讨论】:

  • 将 '@Url.Action("GetCities")' 更改为 "/ControllerName/GetCities"
  • 谢谢 Aditya..for 帮助,但我尝试了“/ControllerName/GetCities”的方式,但它仍然无法正常工作,因为我得到了 URL 未找到的异常...我会尝试按照您的建议进行调试,但请让我知道外部 JS 文件中 URL 问题的替代方案。
  • ControllerName 不只是文本,而是:例如 - 如果您的控制器类名称是 CountryController,那么您应该使用如下 URL:'/Country/GetCities'
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-08-05
  • 1970-01-01
  • 1970-01-01
  • 2014-05-06
  • 1970-01-01
  • 2015-06-02
  • 2021-10-30
相关资源
最近更新 更多