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

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

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

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

调用RenderPage的页面使用一个布局(主)页面,定义了三个部分:TitleContent,HeadContent和Maincontent。 当我试图从这个页面呈现我的语言环境控件时,看起来这些部分也是必需的 – 它们应该只在调用页面中需要并且存在。 我收到以下消息,不pipe是否包含我的部分视图中的部分(显然,我不想包括这些部分,但它似乎是一个有趣的debugging点…)。

以下部分已被定义,但尚未在布局页面“〜/ Views / Shared / LocaleUserControl.cshtml”上呈现:TitleContent; HeadContent; searchMaincontent

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

 @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过程发生。