簡體   English   中英

單擊相應鏈接時如何顯示特定的 MVC 部分視圖?

[英]How to display a specific MVC Partial View when clicking a corresponding link?

我正在使用 MVC 5 和 Visual Studio 2015。我想做一件非常簡單的事情......

我有一個帶有控制器但沒有模型的頁面。 我認為我不需要模型,我沒有訪問或捕獲任何數據; 我只是想根據用戶點擊的內容顯示不同的信息(視圖)。

我在頁面頂部有一個圖標欄(這是它自己的部分),當您單擊一個圖標時,它對應於特定的部分視圖。 單擊另一個圖標,之前的信息將消失並顯示新的信息。 簡單點吧? 我沒有任何運氣。

我發現至少有大量文章解釋了如何為 ONE 部分做到這一點。 但是,如果我想有條件地顯示不在列表中也不在數據庫中的信息,而只是連接到鏈接的部分視圖,該怎么辦?

這是一些代碼......

我的控制器

public class MyController : Controller {

    public ActionResult Index() {
        return View();
    }

    public ActionResult _about() {
        return View();
    }

    public ActionResult _business() {
        return View();
    }
    public ActionResult _finance() {
        return View();
    }
    public ActionResult _jobs() {
        return View();
    }
    public ActionResult _locations() {
        return View();
    }
    public ActionResult _marketing() {
        return View();
    }
    public ActionResult _programming() {
        return View();
    }
}

}

我的索引視圖標記(此頁面的主視圖):

 @using System.Configuration @{ViewBag.Title = "Index";} @Html.Partial("_cteIconBar") <!-- This is the row of icons --> <div class="padding-top-50" id="partial"> @Html.Partial("_about") <!-- I do want to display the "about" partial when a user first lands on the page.--> </div> <div class="padding-top-50" id="partial" style="display: none"> <!-- this is not working... *sigh* --> @{Html.RenderAction("_business"); } @{Html.RenderAction("_programming"); } @{Html.RenderAction("_finance"); } @{Html.RenderAction("_marketing"); } </div>

我的圖標欄標記:

 <div class="row"> <div class="col-lg-12 col-xs-12"> <div class="text-center margin-bottom icon-container"> <ul> <li class="icon-bar-cte" id="about"> <a role="button" href="@Url.Action("_about", "CTE")"> <i class="icon-aboutInfo cte-icon"></i> </a> </li> <li class="icon-bar-cte" id="business"> <a role="button" class="cte-icon" href="@Url.Action("_business", "CTE")"> <i class="icon-business cte-icon"></i> </a> </li> <li class="icon-bar-cte"> <a role="button" href="@Url.Action("_finance", "CTE")"> <i class="icon-finance cte-icon"></i> </a> </li> <li class="icon-bar-cte"> <a role="button" href="@Url.Action("_marketing", "CTE")"> <i class="icon-marketing cte-icon"></i> </a> </li> <li class="icon-bar-cte"> <a role="button" href="@Url.Action("_programming", "CTE")"> <i class="icon-programming cte-icon"></i> </a> </li> <li class="icon-bar-cte"> <a role="button" href="@Url.Action("_jobs", "CTE")"> <i class="icon-jobs cte-icon"></i> </a> </li> <li class="icon-bar-cte"> <a role="button" href="@Url.Action("_locations", "CTE")"> <i class="icon-location-marker cte-icon"></i> </a> </li> </ul> </div> </div> </div>

我對其中一個部分的標記(它們都相同,但單詞不同)。 我用一點“嬉皮 Ipsum”代替了你的樂趣。

 <div class="container collapse in" id="about" aria-expanded="true"> <div class="row padding-bottom-50"> <div class="col-lg-8 col-lg-offset-2 col-md-8 col-md-offset-2 col-sm-12"> <h2 class="green">Some Hippie Ipsum for You!</h2> <p><strong>What is Career Technical Education?</strong></p> <p>Equinox plant consciousness midwifery embracing and moving towards djembe craniosacral, dolphin Hafiz ecstatic dance higher cosmic force spoken word. Prayer flags fair trade what quantum theory says, healing tonic non-profit co-create impermanent hemp seed.</p> <br /> <p><strong>Why is Hippie Ipsum important?</strong></p> <p>Closing circle himalayan sea salt multi-dimensional honoring your truth, forest birth name. Tofurkey native american ancestry diva cup human potential yoni, bioneers the buddha sunset. Animal totem deep cleansing emotional release one taste life coach compostable toilet, be the change astrological mercury retrograde holistic.</p> </div> </div> </div>

 .padding-top-50{ padding-top:50px; }

您想要實現的最簡單的解決方案是使用 AJAX,這樣您就可以將視圖注入到容器中。

所以讓我們從頭開始:

1) 你必須返回 PartialView() 而不是普通的 View()

public ActionResult _about() {
    return PartialView();
}

2) 不需要,但我會更改菜單標記中的一些內容。 注意data-url而不是href

<li class="icon-bar-cte" id="business">
    <a href="#" role="button" class="cte-icon" data-url="@Url.Action("_business", "CTE")">
        <i class="icon-business cte-icon"></i>
    </a>
</li>

3)最重要的部分是下面的jQuery。 根據您的需要,您可以在注入視圖時使用append而不是html

$(document).on('click','.cte-icon',function(e){
    e.preventDefault();

    var url = $(this).data('url');
    $.ajax({
       url: url,
       type: 'GET'
    }).done(function(response){
       $('#partial').html(response);
    });
});

還有另一種方式,如果您想要更“普通”的 .NET MVC 是使用 actionlinks 並從您的控制器操作返回部分視圖。 像這樣的東西:

public ActionResult _programming() 
{
        PartialView("~/Views/YourPartialsPath/_programming.cshtml");
}

在你看來,把這個:

    @Html.ActionLink("Html element text", 
                     "_programming", 
                     "MyController", 
                      new { controller = "MyController" }, 
                      new { @class = "MaybeYouWantAClassOnTheHtmlElement" })

如果您願意,您可以通過最初加載一個視圖作為您的“基本結構”容器來將您的網站構建為一個單頁應用程序。 然后,該頁面將加載一組可能包含側面/頂部菜單欄和“主頁”容器的部分。 這個主頁也可以負責加載一些你想要在所有以后加載的部分中運行的 javascripts(可能是一個顯示/隱藏 ajax.gif 圖像的函數)

假設您將其放在初始頁面加載中。 也許你把它放在你的:\\Views\\Home\\index.cshtml 甚至你的:\\Views_Layout.cshtml

        <div id="navbar" class="navbar-collapse collapse">
            <ul class="nav navbar-nav navbar-left">
                @{ Html.RenderAction("TopMenuRenderer", "Menu");}
            </ul>
            <ul class="nav navbar-nav navbar-right">
                @{ Html.RenderAction("UserMenuRenderer", "Menu");}
            </ul>
        </div>

然后創建一個名為 Menu 的控制器

namespace WebPortal.Web.Controllers
{
    public class MenuController : Controller
    {
        [ChildActionOnly] //for ajax call to controller remove this annotation
        public ActionResult TopMenuRenderer()
        {
            //return PartialView();
            if (User.IsInRole(Role.Admin.ToString()) ||
                User.IsInRole(Role.SuperAdmin.ToString()))
            {
                return PartialView("~/Views/Menu/_TopMenu.cshtml");
            }
            return null;
        }

        [ChildActionOnly]
        public ActionResult UserMenuRenderer()
        {
            if (User.Identity.IsAuthenticated)
                return PartialView("~/Views/Menu/_UserMenuAuthenticated.cshtml");
            else
                return PartialView("~/Views/Menu/_UserMenuNotAuthenticated.cshtml");
        }
        [ChildActionOnly] 
        public ActionResult SideMenuRenderer()
        {
            //you could put some user checks here if you want to limit some of the loaded meny options depending on the user type.
            if (User.IsInRole(Role.Admin.ToString()) ||
                User.IsInRole(Role.SuperAdmin.ToString()))
            {
                return PartialView("~/Views/Menu/_SideMenu.cshtml");
            }
            return null;
        }
}     

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM