我的主佈局的一部分有一個下拉菜單,其中包含指向某些用戶設置的模式面板的鏈接。我不知道如何做到這一點,但到目前爲止,我已經試過如下:在佈局中使用自己的控制器渲染局部視圖
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