我的主布局的一部分有一个下拉菜单,其中包含指向某些用户设置的模式面板的链接。我不知道如何做到这一点,但到目前为止,我已经试过如下:在布局中使用自己的控制器渲染局部视图
UserController.cs
public class UserController : Controller
{
//
// GET: /UserProfile/
[ChildActionOnly]
public ActionResult UserProfile(string user)
{
ViewBag.UserName = user;
return View();
}
}
UserProfile.cshtml
<h4>
Modal Header
</h4>
<p class="help-block">Dummy text</p>
<hr>
@ViewBag.UserName
_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>
每当我尝试运行此我得到的线在我_Layout.cshtml
未处理的异常,我打电话给我的@{ Html.Action("UserProfile", "User", new { user = @ViewBag.UserName }); }
:
An unhandled exception of type 'System.StackOverflowException' occurred in System.Web.Mvc.dll
我怎么呈现的观点也是这样吗?很显然,我正在做一些根本性错误的事情。
这似乎是工作!我可以如此大胆地要求解释为什么我的ViewBag.UserName为空?我能否以某种方式延迟对UserProfile的调用?或者甚至更好,当模式打开时触发它? –
您可以通过简单的ajax调用来处理它,方法是删除ChildActionAttribute并使用jQuery.get; ViewBag.UserName可以为null,因为您在分配值之前使用它。 – archil