【问题标题】:AJAX not working in ASP .Net MVCAJAX 在 ASP .Net MVC 中不起作用
【发布时间】:2016-02-29 19:52:21
【问题描述】:

我不太了解如何执行 AJAX 或者在部分视图的情况下使用 jQuery。这是我面临的问题:

在我看来 MyAction.cshtml 接收 StudentViewModel 对象的集合:

@model IEnumerable<MvcApplication4.ViewModels.StudentViewModel>  
@{
    ViewBag.Title = "MyAction";
    Layout = "~/Views/Shared/_myTemplateLayoutPage.cshtml";
}

<script type="text/javascript" src="/scripts/jquery-1.3.2.js"></script>
<script type="text/javascript">
    $('.editDetails').click(function () {
        alert('Edit Clicked');
    });
</script>

<div id="content">
    <div id="mainpage">

    <h2>Registration Details</h2>
        <ul>
        @foreach(var item in Model) 
        {
            <li>
                @Ajax.ActionLink(item.UserName, 
                "GetUserDetails",
                new { id = item.Student.StudentId },
                    new AjaxOptions
                    {
                        UpdateTargetId = "StudentDetails", 
                        InsertionMode = InsertionMode.Replace,
                        HttpMethod = "GET" @*HTTP method *@
                    }
                )
            </li>
        }
        </ul>
        <div id ="StudentDetails"></div>
    </div>
    <div id="sidebar">
    </div>
    <div id="sidebarbottom"></div>
</div>

我有某些用户名超链接,它们本质上是 ajax 操作链接。当单击 GetUserDetails 时,控制器操作方法被触发,该方法返回包含 StudentViewModel 对象详细信息的特定局部视图。

    [HttpGet]
    public PartialViewResult GetUserDetails(int? id)
    {
        StudentContext context = new StudentContext();

        var result = context.Students.Where(s => s.StudentId == id)
            .Include(s => s.Department)
            .Select(s => new StudentViewModel
                {
                    Student = s,
                    UserName = s.UserName,
                    DepartmentName = s.Department.DepartmentName
                }).First();

        return PartialView("_StudentDetails",result);

    }

部分视图 _StudentDetails 看起来像:

@model MvcApplication4.ViewModels.StudentViewModel

<h2>Student Details</h2>
<table border="1">
    <tr>
        <th>
            Name
        </th>
        <th>
            User Name
        </th>
        <th>
            Department
        </th>
        <th colspan="2">
            Actions
        </th>
    </tr>
    <tr>
        <td>
            @Html.DisplayFor(x => x.StudentFullName)
        </td>
        <td>
            @Html.DisplayFor(x => x.UserName)
        </td>
        <td>
            @Html.DisplayFor( x => x.DepartmentName)
        </td>
        <td>
            <input type="submit" class="editDetails" value="Edit Details" name="Command" />
        </td>
        <td>
            <input type="submit" class="addDetails" value="Add Details" name="Command" />
        </td>
    </tr>
</table>

它们完全按照预期的方式呈现。部分视图在 StudentDetails div id 中呈现。

现在,当我单击编辑按钮时,警报不会被触发。

    <script type="text/javascript" src="/scripts/jquery-1.3.2.js"></script>
    <script type="text/javascript">
    $('.editDetails').click(function () {
        alert('Edit Clicked');
    });
</script>

我错过了什么?

已处理 _myTemplateLayoutPage.cshtml 中的引用。

Google chrome 在控制台日志中显示以下错误。

捆绑配置看起来像:

       public static void RegisterBundles(BundleCollection bundles)
    {
        bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                    "~/Scripts/jquery-{version}.js"));

        bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(
                    "~/Scripts/jquery-ui-{version}.js"));

        bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                    "~/Scripts/jquery.unobtrusive*",
                    "~/Scripts/jquery.validate*"));

        // Use the development version of Modernizr to develop with and learn from. Then, when you're
        // ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
        bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                    "~/Scripts/modernizr-*"));

        bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css"));

        bundles.Add(new StyleBundle("~/Content/themes/base/css").Include(
                    "~/Content/themes/base/jquery.ui.core.css",
                    "~/Content/themes/base/jquery.ui.resizable.css",
                    "~/Content/themes/base/jquery.ui.selectable.css",
                    "~/Content/themes/base/jquery.ui.accordion.css",
                    "~/Content/themes/base/jquery.ui.autocomplete.css",
                    "~/Content/themes/base/jquery.ui.button.css",
                    "~/Content/themes/base/jquery.ui.dialog.css",
                    "~/Content/themes/base/jquery.ui.slider.css",
                    "~/Content/themes/base/jquery.ui.tabs.css",
                    "~/Content/themes/base/jquery.ui.datepicker.css",
                    "~/Content/themes/base/jquery.ui.progressbar.css",
                    "~/Content/themes/base/jquery.ui.theme.css"));
    }

【问题讨论】:

  • 将您的 BundleConfig.cs 添加到您的问题中。
  • 另外,你为什么要引用 jQuery 这么多次?
  • 与显示的错误无关,但肯定与手头的问题有关,即您正在尝试将点击事件绑定到尚不存在的元素。看这里:stackoverflow.com/questions/203198/…
  • 目前还没有运气 :( 请同时查看 BundleConfig.cs。
  • 删除所有对 jQuery 的引用,但不是捆绑包,然后重试。您现在使用的是两个不同的版本

标签: javascript jquery asp.net ajax asp.net-mvc


【解决方案1】:

您正在视图中动态生成编辑按钮(即,它们是在首次加载页面之后添加的 您需要使用event delegation 来处理动态添加的元素。将脚本更改为

$('#StudentDetails').on('click', '.editDetails', function () {
    alert('Edit Clicked');
});

在这种情况下,带有id="StudentDetails" 的元素是页面首次呈现时存在于 DOM 中的最近的祖先。

【讨论】:

    【解决方案2】:

    确保正确加载 jquery。你可以像这样使用cdn。

        <script src="//code.jquery.com/jquery-2.2.1.js"></script>
    

    因为局部视图是动态加载的,所以你必须使用 $(document).on 函数。另外我会将所有内容都放在 document.ready()...

        $(function() {
          $(document).on("click", ".editDetails", function () {
            alert('Edit Clicked');
         });
        });
    

    【讨论】:

      【解决方案3】:

      请将您的 AJAX Actionlink 的 AJAXOptions 替换为以下选项。请注意OnComplete = "RegisterClickHanders"

      <li>
          @Ajax.ActionLink(item.UserName,
          "GetUserDetails",
          new { id = item.Student.StudentId },
              new AjaxOptions
              {
                  UpdateTargetId = "StudentDetails",
                  InsertionMode = InsertionMode.Replace,
                  HttpMethod = "GET" @*HTTP method *@,
                  OnComplete = "RegisterClickHanders"
              }
          )
      </li>
      

      并在您的主页中添加此功能。

      <script>
          function RegisterClickHanders() {
              $('.editDetails').click(function () {
                  alert('Edit Clicked');
              });
          }
      </script>
      

      【讨论】:

      • 不工作。我在我的视图文件 MyAction.cshtml 中添加了部分视图被渲染的部分。
      • @StrugglingCoder 因此,根据您之前的评论,我确信您的捆绑路径是正确的。您的点击处理程序不起作用的原因是您在呈现这些 HTML 元素之前注册它们(它们将在单击学生姓名时动态呈现),这就是您需要订阅 OnComplete 事件的原因。请尝试更新代码,如果您仍然遇到问题,请告诉我。
      • 好的,所以这两个代码块都只在主视图中?
      • 是的,两者都会进入主视图。
      • 你是对的,代码是从上到下执行的,但在你的情况下,因为所有.editDetails 链接都不存在$('.editDetails'). 不会什么都不做。当您单击学生姓名时,将呈现这些链接。此时您的 DOM 已更改,现在您需要订阅 .editDetails 的点击事件。为了测试我正在解释的内容,请在 Chrome 开发人员工具中的 $('.editDetails') 行上设置一个断点,并在控制台内检查它的长度。 Example
      【解决方案4】:

      如果您要将&lt;script&gt; 元素放入您自己,您不能只在其中添加一个 ~ 字符 - 您需要在页面呈现时将其解析为真实的 URL。

      <script src='@Url.Content("~/Scripts/jquery-1.9.1.js")' type='text/javascript'></script>
      

      当然,如果你这样做,你就是在欺骗自己,从捆绑的所有令人敬畏的东西中解脱出来。

      【讨论】:

      • 然而直到现在还没有警报。 :(还有什么需要做的吗?
      • 您的警报是“404”。如果您现在删除捆绑包并使用带有Url.Content 的直接&lt;script&gt; 标签,是否会加载文件,或者您仍然在控制台中获得404?
      • 我没有收到警报。
      • 您在故障排除方面走得太远了。首先,您验证文件正在加载。然后,您担心要执行自己的脚本。
      猜你喜欢
      • 2016-04-07
      • 2014-08-17
      • 1970-01-01
      • 2021-08-04
      • 2016-11-15
      • 2011-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多