简体   繁体   English

单击相应链接时如何显示特定的 MVC 部分视图?

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

I'm using MVC 5 and Visual Studio 2015. I have a very simple thing I want to do...我正在使用 MVC 5 和 Visual Studio 2015。我想做一件非常简单的事情......

I have a page with a controller and NO MODEL.我有一个带有控制器但没有模型的页面。 I don't believe I need a model, I'm not accessing or capturing any data;我认为我不需要模型,我没有访问或捕获任何数据; I simply want to display different information (views) based on what a user clicks.我只是想根据用户点击的内容显示不同的信息(视图)。

I have an icon bar on the top of the page (which is its own partial) and when you click on an icon, it corresponds to a specific partial view.我在页面顶部有一个图标栏(这是它自己的部分),当您单击一个图标时,它对应于特定的部分视图。 Click another icon, the previous info disappears and the new info displays.单击另一个图标,之前的信息将消失并显示新的信息。 Easy peasy right?简单点吧? I'm not having any luck.我没有任何运气。

I've found at least a gazillion articles explaining how to do it for ONE partial.我发现至少有大量文章解释了如何为 ONE 部分做到这一点。 but what if I want to conditionally display info that isn't in a list and isn't in a database, but is simply a partial view connected to a link?但是,如果我想有条件地显示不在列表中也不在数据库中的信息,而只是连接到链接的部分视图,该怎么办?

Here's some of the code...这是一些代码......

My Controller我的控制器

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();
    }
}

} }

My Markup for the Index View (the main view for this page):我的索引视图标记(此页面的主视图):

 @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>

My Markup for the icon bar:我的图标栏标记:

 <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>

My markup for one of the partials (they're all the same with different words).我对其中一个部分的标记(它们都相同,但单词不同)。 I substituted a little "Hippie Ipsum" for your pleasure.我用一点“嬉皮 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; }

The easiest solution for what you'd like to achieve is to use AJAX so you can inject the views into the container.您想要实现的最简单的解决方案是使用 AJAX,这样您就可以将视图注入到容器中。

So let's start from the beginning:所以让我们从头开始:

1) You have to return PartialView() instead of regular View() 1) 你必须返回 PartialView() 而不是普通的 View()

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

2) Not needed, but I'd change some things in your menu markup. 2) 不需要,但我会更改菜单标记中的一些内容。 Note the data-url instead of href .注意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) Most important part is the following jQuery. 3)最重要的部分是下面的jQuery。 Depending of what you need you can use append instead of html when injecting the view.根据您的需要,您可以在注入视图时使用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);
    });
});

Yet another way, if you wanna go more "vanilla" .NET MVC is to use actionlinks and return partial views from your controller actions.还有另一种方式,如果您想要更“普通”的 .NET MVC 是使用 actionlinks 并从您的控制器操作返回部分视图。 Something like this:像这样的东西:

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

And in your views put this:在你看来,把这个:

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

And if you want you could structure your site to be a single page app by initially loading a single view to be your "base structure" container.如果您愿意,您可以通过最初加载一个视图作为您的“基本结构”容器来将您的网站构建为一个单页应用程序。 This page would then load a set of partials consisting of maybe side/top menu bars and maybe a "main page" container.然后,该页面将加载一组可能包含侧面/顶部菜单栏和“主页”容器的部分。 This main page could also be in charge of loading of some javascripts you want to run across all of your later loaded partials (maybe a function showing/hiding an ajax.gif image)这个主页也可以负责加载一些你想要在所有以后加载的部分中运行的 javascripts(可能是一个显示/隐藏 ajax.gif 图像的函数)

Lets say you put this in your initial page load.假设您将其放在初始页面加载中。 Maybe you put this in your: \\Views\\Home\\index.cshtml Or even your: \\Views_Layout.cshtml也许你把它放在你的:\\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>

Then you create a controller called Menu然后创建一个名为 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