如何在视图中加载局部视图? [英] How can I load Partial view inside the view?
问题描述
我对这种片面的看法感到很困惑.
我想在主视图中加载局部视图.
这是一个简单的例子.
我正在加载 Homecontroller Index 操作的 Index.cshtml 作为主页.
在 index.cshtml 中,我通过
创建链接@Html.ActionLink(加载局部视图",加载",首页")
在 HomeController 中,我添加了一个名为
的新动作public PartialViewResult Load(){返回 PartialView("_LoadView");}
在 _LoadView.cshmtl 中我只是有一个
欢迎 !!
但是,当运行项目时,index.cshtml 首先呈现并向我显示链接加载部分视图".当我点击它时,它会进入新页面,将 _LoadView.cshtml 中的欢迎消息呈现到 index.cshtml 中.
有什么问题?
注意:我不想通过 AJAX 加载页面或不想使用 Ajax.ActionLink .
如果你想直接在主视图中加载分部视图,你可以使用 Html.Action
助手:
@Html.Action("加载", "首页")
或者如果您不想执行 Load 操作,请使用 HtmlPartialAsync 帮助程序:
@await Html.PartialAsync("_LoadView")
如果您想使用 Ajax.ActionLink
,请将您的 Html.ActionLink
替换为:
@Ajax.ActionLink(加载局部视图",加载",家",新的 AjaxOptions { UpdateTargetId = "result" })
当然你需要在你的页面中包含一个持有者,其中部分将被显示:
<div id="result"></div>
也不要忘记包括:
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
在您的主视图中以启用 Ajax.*
助手.并确保在您的 web.config 中启用了不显眼的 javascript(默认情况下应该是这样):
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
I am very confuse with this partial view.
I want to load a partial view inside my main view.
Here is the simple example.
I am loading Index.cshtml of the Homecontroller Index action as a main page.
In index.cshtml, I am creating a link via
@Html.ActionLink("load partial view","Load","Home")
in HomeController I am adding a new Action called
public PartialViewResult Load()
{
return PartialView("_LoadView");
}
in _LoadView.cshmtl I am just having a
<div>
Welcome !!
</div>
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.
What can be wrong?
Note: I don't want to load page through AJAX or don't want to use Ajax.ActionLink .
If you want to load the partial view directly inside the main view you could use the Html.Action
helper:
@Html.Action("Load", "Home")
or if you don't want to go through the Load action use the HtmlPartialAsync helper:
@await Html.PartialAsync("_LoadView")
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>
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屋!