[英]Render a partial view with its own controller in layout
A part of my master layout has a dropdown menu that contains a link to a modal panel for some user settings. 我的主版式的一部分有一个下拉菜单,其中包含一些用户设置的模式面板链接。 I'm not sure how to do this, but so far I've tried the following:
我不确定如何执行此操作,但到目前为止,我已经尝试了以下操作:
UserController.cs UserController.cs
public class UserController : Controller
{
//
// GET: /UserProfile/
[ChildActionOnly]
public ActionResult UserProfile(string user)
{
ViewBag.UserName = user;
return View();
}
}
UserProfile.cshtml UserProfile.cshtml
<h4>
Modal Header
</h4>
<p class="help-block">Dummy text</p>
<hr>
@ViewBag.UserName
_Layout.cshtml _Layout.cshtml
<html>
....
<head>...</head>
<body>
<div id="menu">
<li class="userlinks">
<ul class="dropdown-menu">
<li><a data-toggle="modal" href="#usrmodal">View Profile <i class="pull-right fa fa-pencil"></i></a></li>
<li>@Html.ActionLink("Sign Out", "Index", "Logout")</li>
</ul>
</li>
@RenderBody()
</body>
<!-- Modal -->
<div class="modal fade" id="usrmodal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">User Settings</h4>
</div>
<div class="modal-body">
@{ Html.Action("UserProfile", "User", new { user = @ViewBag.UserName }); }
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
</html>
Whenever I try to run this I get an unhandled exception at the line in my _Layout.cshtml
where I call my @{ Html.Action("UserProfile", "User", new { user = @ViewBag.UserName }); }
每当我尝试运行此
_Layout.cshtml
,我在_Layout.cshtml
中的行上都会得到未处理的异常,该行将我的@{ Html.Action("UserProfile", "User", new { user = @ViewBag.UserName }); }
@{ Html.Action("UserProfile", "User", new { user = @ViewBag.UserName }); }
: @{ Html.Action("UserProfile", "User", new { user = @ViewBag.UserName }); }
:
An unhandled exception of type 'System.StackOverflowException' occurred in System.Web.Mvc.dll
How am I supposed to render views like this? 我应该如何渲染这样的视图? Obviously I'm doing something fundamentally wrong.
显然我在做一些根本错误的事情。
View()
renders with Layout, so you get stack overflow. View()
使用Layout渲染,因此您会得到堆栈溢出。 return PartialView();
should help you. 应该可以帮助您。
[ChildActionOnly]
public ActionResult UserProfile(string user)
{
ViewBag.UserName = user;
return PartialView();
}
尝试将ViewBag.UserName强制转换为字符串
@Html.Action("UserProfile", "User", new { user = (string)ViewBag.UserName });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.