首页 > 解决方案 > 从超链接渲染局部视图

问题描述

我有一个 ASP.NET Core MVC Web 应用程序。

我的 Index.html 页面中有这个:

<div class="carousel-caption" role="option">
    <p>
        Upgrade your Legacy VB6 Applications to .Net Core!
        <a class="btn btn-default" id="VB6Upgrades">
            Learn More
        </a>
    </p>
</div>

<div id="MainContent" class="row">

</div>

我的 JS 文件:

$("#VB6Upgrades").click(function () {
    $.get('@Url.Action("LoadVB6Upgrades","/Home")', {}, function (response) {
        $("#MainContent").html(response);
    });
});

我的控制器:

public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }

    public IActionResult Error()
    {
        ViewData["RequestId"] = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
        return View();
    }

    public IActionResult LoadVB6Upgrades()
    {
        return PartialView("_LoadVB6Upgrades");
    }
}

当我单击我的链接时,会调用 Index() 函数吗?

请问我该怎么办?

标签: jqueryajaxasp.net-corepartial-views

解决方案


您必须将数据类型设置为 html 才能在 div 中加载部分视图。默认数据类型是 json 你可以在这里查看stackoverflow.com/questions/30953714/whats-default-datatype-of-jquerys-ajax-and-get-methods

  $("#VB6Upgrades").click(function () {
      $.ajax({
            type: "GET",
            url: '@Url.Action("LoadVB6Upgrades","Home")',
            dataType: "html",
            success: function (result) {
                if (result) {
                     $("#MainContent").html(result);
                }
            },
            error: function (result) {
             $("#MainContent").html('');
            }
        });
    });

推荐阅读