如何在视图内加载局部视图? [英] How can I load Partial view inside the view?

查看:77
本文介绍了如何在视图内加载局部视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对这种局部视图非常困惑.

I am very confuse with this partial view.

我想在主视图中加载局部视图.

I want to load a partial view inside my main view.

这是简单的例子.

我正在将Homecontroller Index操作的Index.cshtml加载为主页面.

I am loading Index.cshtml of the Homecontroller Index action as a main page.

在index.cshtml中,我通过创建链接

In index.cshtml, I am creating a link via

@Html.ActionLink("load partial view","Load","Home")

在HomeController中,我添加了一个新的动作

in HomeController I am adding a new Action called

public PartialViewResult Load()
{
    return PartialView("_LoadView");
}

在_LoadView.cshmtl中,我只有一个

in _LoadView.cshmtl I am just having a

<div>
    Welcome !!
</div>

但是,当运行项目时,index.cshtml首先呈现,并向我显示链接"Load Partial View".当我单击它时,它将转到新页面,以将欢迎消息从_LoadView.cshtml呈现到index.cshtml.

BUT, when run the project, index.cshtml renders first and shows me the link "Load Partial View". when I click on that it goes to new page instade of rendering the welcome message from _LoadView.cshtml into the index.cshtml.

有什么问题吗?

注意:我不想通过AJAX加载页面或不想使用Ajax.ActionLink.

Note: I don't want to load page through AJAX or don't want to use Ajax.ActionLink .

推荐答案

如果您想直接在主视图中加载部分视图,则可以使用 Html.Action 助手:

If you want to load the partial view directly inside the main view you could use the Html.Action helper:

@Html.Action("Load", "Home")

或者如果您不想执行加载"操作,请使用HtmlPartialAsync帮助器:

or if you don't want to go through the Load action use the HtmlPartialAsync helper:

@await Html.PartialAsync("_LoadView")

如果要使用 Ajax.ActionLink ,请将您的 Html.ActionLink 替换为:

If you want to use Ajax.ActionLink, replace your Html.ActionLink with:

@Ajax.ActionLink(
    "load partial view", 
    "Load", 
    "Home", 
    new AjaxOptions { UpdateTargetId = "result" }
)

当然,您需要在要显示部分内容的页面中包含一个支架:

and of course you need to include a holder in your page where the partial will be displayed:

<div id="result"></div>

也不要忘记包括以下内容:

Also don't forget to include:

<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>

在主视图中

以便启用 Ajax.* 帮助器.并确保在您的web.config中启用了兼容的javascript(默认情况下应启用):

in your main view in order to enable Ajax.* helpers. And make sure that unobtrusive javascript is enabled in your web.config (it should be by default):

<add key="UnobtrusiveJavaScriptEnabled" value="true" />

这篇关于如何在视图内加载局部视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆