在布局中使用自己的控制器渲染局部视图

时间:2013-12-20 13:01:05

标签: c# asp.net-mvc razor asp.net-mvc-5

我的主布局的一部分有一个下拉菜单,其中包含指向某些用户设置的模式面板的链接。我不知道该怎么做,但到目前为止我已经尝试了以下内容:

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">&times;</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

我该如何渲染这样的视图?显然我正在做一些根本错误的事情。

2 个答案:

答案 0 :(得分:3)

View()使用Layout进行渲染,因此会出现堆栈溢出。 return PartialView();应该会帮助你。

[ChildActionOnly]
public ActionResult UserProfile(string user)
{
    ViewBag.UserName = user;
    return PartialView();
}

答案 1 :(得分:0)

尝试将ViewBag.UserName强制转换为字符串

@Html.Action("UserProfile", "User", new { user = (string)ViewBag.UserName });