使用JQuery动态加载ASP.NET MVC局部视图

3

我有一个视图,左侧有一个测试链接。每次用户点击测试链接时,我会添加一个选项卡按钮和选项卡内容(纯HTML5和CSS)。它看起来像这样:

enter image description here

控制器代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MDMS_Web.Controllers
{
    public class MainViewController : Controller
    {
        //
        // GET: /MainView/

        public ActionResult MainView(string name)
        {
            ViewBag.Name = name;

            return View();
        }

        //[ChildActionOnly]
        //public PartialViewResult MainContentPartial()
        //{
        //    return PartialView("~/Views/MainView/MainContentPartial.cshtml");
        //}

        public ActionResult GetView()
        {
            return PartialView("~/Views/MainView/MainContentPartial.cshtml");
        }

    }
}

Partial View

<div id="MainContentBox" style="margin: 0em 0em;">
    <h2>Testing</h2>
</div>

主视图

@{
    ViewBag.Title = "Main View";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<main id="mainView">
    <div class="row" style="min-width: 100%; ">

        <div style="float: left; width: 20%; min-height: 870px; margin-top: 0.5em; margin-left: -1em; overflow: hidden; border-style: solid; border-width: thin; border-color: lightgray; ">
            <div id="Test">
                <div class="row" style="background-color: #c2cbfb; margin-left: 0; margin-right: 0; ">
                    <p id="menuTitle" style="width: 100%; text-align: center; margin: 5px 0 5px 0; ">Test</p>
                </div>
                <div class="row content-wrapper">
                    <span style="white-space: nowrap;">
                        <img class="icon" style="width: 30px; height: 30px; " src="Content/images/dashboard/CheckIcon.png" alt="Check icon" />
                        <a id="TestLink">Test Stuff</a>
                    </span>
                </div>
            </div>
        </div>

        <div style="float: left; width: 80%; min-height: 870px; margin-top: 0.5em; margin-left: 0em; overflow: hidden; ">
            <div id="MainContentBox" style="margin: 0em 0em;">
                <div id="tabs" class="tab">

                </div>

                <div id="content">

                </div>
            </div>
        </div>
    </div>


    <div id="loading">

    </div>

</main>

@section scripts{

    @Scripts.Render("~/bundles/App/MainView")

    <script type="text/javascript">
        $(function () { MainView.initModule('@ViewBag.Name') });
    </script>
}

JavaScript

function addTab(evt) {
    stateMap.tabIndex += 1;

    // add tab button
    console.log(evt);
    var tHtml = '<button id="tb' + stateMap.tabIndex + '" class="tablinks">' + "New Tab " + stateMap.tabIndex + '</button>';
    $("#tabs").append(tHtml);

    console.log("we have a new tab!");

    // add tab content section
    var node = document.createElement('div');
    node.setAttribute('id', 't' + stateMap.tabIndex);
    node.className = "tabContent";

    // load partial page place holder
    var contentPlaceHolder = document.createElement('div');
    contentPlaceHolder.setAttribute('id', 'c' + stateMap.tabIndex);
    node.appendChild(contentPlaceHolder);
    document.getElementById("content").appendChild(node);

    console.log("we have new content placeholder for partial view!");


 // HERE IS WHERE MY PROBLEM BEGINS !!!!!!
 // NOTHING I DO WILL LOAD MY PARTIAL PAGE !!!!


    //@{ Html.RenderPartial("MainContentPartial"); }
    //$("#c" + stateMap.tabIndex).load('@{ Html.RenderPartial("MainContentPartial"); }');
    //$("#c" + stateMap.tabIndex).load("GetView");
    $(function () {
        $("#c" + stateMap.tabIndex).load(
            '<%= Url.Action("GetView", "MainViewController") %>'
        );
    })
    //url: 'MainViewController/GetView',
    //$.ajax({
    //    url: 'GetView',
    //    dataType: 'html',
    //    success: function (data) {
    //        $("#c" + stateMap.tabIndex).html(data);
    //    }
    //});
}

JavaScript initModule

var initModule = function (data) { 
    stateMap.currentSection = data;

    //Bind events
    $("#TestLink").on("click", function (event) {
        addTab(event);
    });

    $(document).ready(function () {
        $(".tab").on("click", "button", function (event) {
            openTab(event);
        });
    });

};

return { initModule: initModule };

我的问题出现在 JavaScript 的最后一部分,可能是控制器的问题。 请问有人能告诉我使用 JQuery 正确地将局部视图加载到我动态创建的选项卡内容中的方法吗?


1
你在哪里调用了 addTab 方法? - Shyju
1
你的代码会出现404(未找到)错误 - 应该是 Url.Action("GetView", "MainView"),而不是 "MainViewController" - user3559349
1
你真的在使用aspx而不是razor吗?从你的编辑中看,你的脚本在外部文件中,这意味着你需要使用$("#c" + stateMap.tabIndex).load('/MainView/GetView');,(Url.Action是服务器端代码,不会在外部js文件中解析)。 - user3559349
1
但更好的选择是在主视图中使用 Url.Action() 生成 URL 并将其传递给脚本。 - user3559349
1
此外,您不需要在.load()方法周围加上$(function () { - user3559349
显示剩余9条评论
1个回答

4
您可以使用Jquery以以下方式动态加载Partial View。
$(document).on("click", "#TestLink", function () {
        var url = "/MainView/GetView";
        $.get(url, function (data) {
            $("#content").html(data);
        });
 });

这里的URL是一个动作的网址,它将返回PartialView。

1
这个url和.load语法对我来说很困惑。所以,我想确保我理解正确。对于var url = '@Url.Action("GetView", "MainView")';,第一个参数是PartialViewResult方法名称,第二个参数是ActionResult方法名称吗?而对于var url = "/MainView/GetView";,MainView是控制器中的ActionResult方法名称,GetView是控制器中的PartialViewResult方法名称吗? - Patricia
1
是的,你说得对,这里的 MainView 是控制器名称,而 GetView 是其返回 PartialView 的操作。如果你在 .cshtml 页面中编写此 js 函数,可以使用 var url='@Url.Action("GetView", "MainView")',但如果它在单独的文件中,则必须使用 '/MainView/GetView' - Waqas Idrees

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接