Asp.net MVC Core - 无法使用Ajax加载部分视图

时间:2017-01-31 01:16:54

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

关注此article后,我无法通过Partial View加载Ajax。但它没有加载partial view

注意:

  1. 我正在使用VS2015的最新更新,以及Visual Studio的MVC Core Web应用程序项目模板附带的Jquery的默认安装/配置。
  2. Google Chrome的开发者工具显示没有错误。并且,浏览器的视图源仍显示<div id="UpdateTabData"></div>标记为空
  3. 我已经通过将alert('Test')置于Ajax调用中的click事件中并使用breakpoint内部控制器操作方法进行测试,Ajax确实正在调用TestAction方法并且该方法确实已返回return PartialView("PartialView", myViemodel);在操作方法中没有任何错误。
  4. 但最后的Ajax从它的错误函数
  5. 返回我的自定义错误消息

    控制器

    [HttpGet]
    public IActionResult TestAction(string calledFrom)
    {
      ... some code here with a view model myViemodel
    
      return PartialView("myPartialViewName", myViemodel);
    }
    

    查看:

    @model myProj.Models.myTestViewModel
    ...some html here...
    <div id="UpdateTabData"></div>
    ... more html here
    ...
    

    视图末尾的Ajax代码

    $(document).ready(function () {
    
        $('#myTabstripID li').click(function () {
            var li_id = $(this).attr("id");
    
            $.ajax({
                url: '@Url.Action("TestAction", "myControllerName")',
                data: { calledFrom: li_id},
                contentType: 'application/json',
                dataType: 'html'
                type: 'GET',
                cache: false,
                success: function (data) {
                    $('#UpdateTabData').html(data);
                },
                error: function (data) {
                    alert('Error occurred');
                }
            });
        });
    
    });
    

2 个答案:

答案 0 :(得分:0)

  1. 按f12并检查应返回部分视图的操作的URL。
  2. 复制该网址并将其粘贴到浏览器地址栏,按Enter键。
  3. 您将看到错误(如果有错误)或部分视图。
  4. 如果第3步没有错误,请尝试输入alert($(&#39;#UpdateTabData&#39;)。length);在控制台中(如果你真的有一个具有这种id的元素,则应为1);
  5. 这是一个非常简单的任务(我的意思是获得一些返回局部视图的动作结果),所以它应该可行。所以你可能在某个地方有错误的id或类似的东西。

答案 1 :(得分:0)

您可以删除此部分代码。

contentType: 'application/json',

根据控制器中的ActionResult,您将返回部分视图。所以你的ajax调用期望一个视图而不是json。这将解决您的问题。