将许多相似的视图转换为局部视图

问题描述 投票:0回答:1

我正在更新一个项目,其中许多不同的视图共享相同的布局,并且它们之间的内容只有很小的差异。

基本布局如下:

@Html.Partial("_HeadingBar")

<div class="panel grid_4">

    <div class="panel-header">
        <span>@ViewBag.SmallHeader</span>
    </div>

    <div class="panel-body">
        <div class="panel-content">
            @* Welcome.cshtml:
            <p>Please use the navigation bar on the side of the site to utilize the features of the site.</p> *@

            @* Login.cshtml:
            @using (Html.BeginForm())
            {
                if (!ViewData.ModelState.IsValid) ...

                <div class="form-row-inline">
                    @Html.LabelFor(m => m.UserName)
                    @Html.TextBoxFor(m => m.UserName)
                    @Html.ValidationMessageFor(m => m.UserName)
                </div>
                ...
                <button type="submit" class="btn btn-success"><i class="icon-lock"></i> Sign In</button>
            } *@

            @* ChangePassword.cshtml:
            @using(Html.BeginForm())
            {
                ...
                @Html.LabelFor(m => m.NewPassword)
                @Html.PasswordFor(m => m.NewPassword)
                @Html.ValidationMessageFor(m => m.NewPassword)
                ...
            } *@


        </div>
    </div>
</div>

我的想法是将每个视图分解为唯一的内容,并使其成为部分视图,并使共享的部分成为常规视图。

但是我不确定这是正确的方法。添加Html.RenderPartial将导致对服务器的第二次调用,并且需要将其他操作添加到Controller。

似乎我正在寻找布局,但该网站已使用布局。

处理此问题的正确/最佳做法是什么?

asp.net-mvc asp.net-mvc-partialview asp.net-mvc-layout
1个回答
0
投票

我认为您正朝正确的方向前进。我个人将大视图拆分为较小的功能,这也意味着控制器等更易于阅读和维护。

除非包含缓存,否则所有辅助方法(包括HtmlRenderPartial都会在收到请求时在服务器端呈现)。因此不应再有其他呼叫服务器。

有几种可以使用的html帮助器方法

没有控制器的部分

@Html.Partial("~/Views/Shared/Partials/SomePartialViewWithNoModel.cshtml")
@Html.Partial("~/Views/Shared/Partials/SomePartialViewWithModel.cshtml", Model)

带有控制器的部分

@Html.Action("RenderPartial", "ControllerWithNoModelMethod")
@Html.Action("RenderPartial", "ControllerWithModelMethod", new { content = Model })
© www.soinside.com 2019 - 2024. All rights reserved.