繁体   English   中英

剃刀视图引擎 - 如何添加部分视图

[英]Razor view engine - How can I add Partial Views

我想知道,如果可能的话,使用新的剃刀视图引擎渲染局部的最佳方法。 我知道这是当时没有完全完成的事情

现在我使用RenderPage来呈现用户控件:

@RenderPage("~/Views/Shared/LocaleUserControl.cshtml",ViewData.Model)

调用RenderPage的页面使用布局(主)页面,其中定义了三个部分:TitleContent,HeadContent和Maincontent。 当我尝试从此页面渲染我的语言环境控件时,似乎还需要这些部分 - 它们应该只在调用页面中需要并且存在。 我收到以下消息,无论我是否在部分视图中包含这些部分(显然我不想包含这些部分,但它似乎是一个有趣的调试点......)。

以下部分已定义,但尚未在布局页面'〜/ Views / Shared / LocaleUserControl.cshtml'上呈现:TitleContent; HeadContent; 搜索Maincontent

我的部分观点如下(改编自以下链接 ):

@inherits System.Web.Mvc.WebViewPage<LocaleBaseModel>
@using System.Web.UI;

<p>
     @Html.LabelFor(model => Model.CountryName)
    <br />
    @Html.DropDownListFor(model => Model.CountryName,null, string.Empty, new { @class = "text", accesskey="u"})
</p>
<p>
     @Html.LabelFor(model => Model.StateProvince)
    <br />
     @Html.DropDownListFor(model => Model.StateProvince, null, string.Empty, new { @class = "text", accesskey="t" })
</p>


<script type="text/javascript">
    $(function () {
        var countries = $("#CountryName");
        var statesprovinces = $("#StateProvince");
        countries.change(function () {
            statesprovinces.find('option').remove();
            var url = '@Url.Action("GetStatesProvinces", "Base")';
            $.getJSON(url, { countryId: countries.val() }, function (data) {
                $(data).each(function () {
                    $("<option value=" + this.ID + ">" + this.Name + "</option>").appendTo(statesprovinces);
                });
            });
        });
    });
</script>

你看起来很像编辑器模板,所以你可以这样包含它(假设你的部分放在~/views/controllername/EditorTemplates子文件夹中):

@Html.EditorFor(model => model.SomePropertyOfTypeLocaleBaseModel)

或者如果不是这种情况:

@Html.Partial("nameOfPartial", Model)

如果您不想复制代码,并且像我一样,您只想显示统计信息,那么您可以在视图模型中传递要从中获取数据的模型,如下所示:

public class GameViewModel
{
    public virtual Ship Ship { get; set; }
    public virtual GamePlayer GamePlayer { get; set; }     
}

然后,在您的控制器中,只需在相应的模型上运行查询,将它们传递给视图模型并返回它,例如:

GameViewModel PlayerStats = new GameViewModel();

GamePlayer currentPlayer = (from c in db.GamePlayer [more queries]).FirstOrDefault();

[检查结果的代码]

//pass current player into custom view model
PlayerStats.GamePlayer = currentPlayer;

就像我说的那样,如果你想显示相关表格中的统计数据,你应该真的这样做,并且出于其他人在上面提到的安全原因,没有CRUD过程的其他部分发生。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM