使用JQuery在mvc中加载局部视图

时间:2018-06-06 11:43:47

标签: jquery asp.net-mvc

我正在尝试使用this question为我的布局添加部分视图。

我有以下相关代码:

ShowStatistics.cshtml

 <script src="/scripts/jquery-3.3.1.js" type="text/javascript"></script>
    <script>


$(document).ready(function () {
        $('.jsload').on('click', function (evt) {
                evt.preventDefault();
                evt.stopPropagation();

            var $detailDiv = $('#detailsDiv'),
                url = $(this).data('url');

            $.get(url, function (data) {
                $detailDiv.replaceWith(data);
            });
        });
})
</script>

<div id="detailsDiv">
            <!--Content gets loaded by JQuery-->
</div>
        <button data-url='@Url.Action("Details","Statistics", new { id = Model.Id } )' class="jsload">
            Show Skills
        </button>

PlayerSkills.cshtml

@model MVC.Models.ViewPlayerSkills
@{
    Layout = null;
}
<p>HAHAHAHAHAHAHHAHAHAHHAHAHAHAHHAH</p>
@foreach (var property in ViewData.ModelMetadata.Properties)
{
    <div class="editor">
        <label>@(property.DisplayName ?? property.PropertyName):</label>
        @Html.Display(property.PropertyName)
    </div>
}

StatisticsController.cs

        public ActionResult Details(int id)
    {
        List<Player> allPlayers = GetPlayers();
        Player pl = allPlayers.Where(x => x.Id == id).FirstOrDefault();
        ViewPlayerSkills player = new ViewPlayerSkills(pl);
        return PartialView("PlayerSkills", player);

    }

我收到以下错误消息:

  

未捕获的ReferenceError:未定义数据       在Object.success(3:21)       在火上(jquery-3.3.1.js:3268)       at Object.fireWith [as resolveWith](jquery-3.3.1.js:3398)       完成后(jquery-3.3.1.js:9305)       在XMLHttpRequest。 (jquery-3.3.1.js:9548)(匿名)@ 3:21 fire @ jquery-3.3.1.js:3268 fireWith @jquery-3.3.1.js:3398完成   @jquery-3.3.1.js:9305(匿名)@jquery-3.3.1.js:9548加载(异步)   发送@jquery-3.3.1.js:9567 ajax @jquery-3.3.1.js:9206   jQuery。(匿名函数)@jquery-3.3.1.js:9355(匿名)@ 3:20   dispatch @ jquery-3.3.1.js:5183 elemData.handle @jquery-3.3.1.js:4991

当我转到网址http://localhost:{port} / Statistics / Details / 5

我得到了我想要的输出:

Output

1 个答案:

答案 0 :(得分:1)

<script src="/scripts/jquery-3.3.1.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $('.jsload').on('click', function (evt) {
            evt.preventDefault();
            evt.stopPropagation();;
            $('#detailsDiv').load($(this).data('url'));
        });
    })
</script>
<div id="detailsDiv">
    <!--Content gets loaded by JQuery-->
</div>
<button data-url='@Url.Action("Details","Statistics", new { id = Model.Id } 
)' class="jsload">
  Show Skills
</button>