【发布时间】:2011-08-18 15:43:03
【问题描述】:
我正在将 MVC2 应用程序转换为 MVC3。 我似乎无法将视图与编辑器模板结合起来。 所以在我看来,代码是;
@model IEnumerable<ITOF.Models.LatestContractNumber>
@{
ViewBag.Title = "EditContractNumbers";
Layout = "~/Views/Shared/_Layout.cshtml";
}
using (Html.BeginForm())
{
<fieldset>
<legend>Edit Latest Contract Numbers</legend>
<div style="width:90%">
<div style="width:45%; float:left; vertical-align:top;">
<p>A contract number is in a format: AA/B999</p>
<p>Where AA is a 2 character code for the division, for example CD.</p>
<p>Where B is a letter for the contract, usually the first letter of the contract title.</p>
<p>999 is a 3 digit number.</p>
<p>The 999 number depends on the B letter. </p>
<p>Initially all the numbers start as 1 and are incremented each time the B letter is used.</p>
<p>This pages sets the initial 999 number for each B letter.</p>
<p>Once the application is up and running, this page should be used initially and then no more.</p>
@if (TempData["Message"] != null && TempData["Message"].ToString().Trim().Length > 0)
{
<p class="success">@TempData["Message"].ToString()</p>
}
</div>
<div style="width:45%; float:right; vertical-align:top;">
<div>
<table>
<tr>
<td>Letter</td>
<td>Number</td>
</tr>
@Html.EditorForModel(Model)
</table>
</div>
<div style="padding-top:20px">
<input type="submit" value="Submit Changes" />
</div>
</div>
</div>
</fieldset>
}
我的编辑器模板位于正确的文件夹中,现在看起来像;
@model ITOF.Models.LatestContractNumber
<tr>
<td>
@Html.HiddenFor(model => model.LatestContractNumberId)
@Html.DisplayFor(model => model.Letter)
</td>
<td>
@Html.TextBoxFor(model => model.Number, new { style = "width:30px" })
</td>
</tr>
@Html.EditorForModel(Model) 中的模型与页面顶部的@model IEnumerable 相关。 在编辑器模板中,这应该转换为 ITOF.Models.LatestContractNumber 的循环,因此我在模板的顶部放置了@model ITOF.Models.LatestContractNumber
【问题讨论】:
-
当您说您的编辑器模板位于正确的文件夹中时,它到底在哪个文件夹中?
-
Editor Templates 文件夹,该文件夹又位于与视图相同的文件夹中。
-
EditorTemplate 文件的名称是什么?
-
好问题!我养成了在名称前面以 _ 开头的每个局部视图的习惯,但对于名称必须与模型名称匹配的编辑器模板,这当然不起作用。所以我已将 _LatestContractNumber.cshtml 更改为 LatestContractNumber.cshtml,现在它可以工作了!如果您希望我奖励您正确的答案,请将其作为答案。
-
您的
@Html.EditorForModel(Model)调用将模型作为附加视图数据传递——您不需要将模型传递给它。以_开头的模板是个好主意,因为最终用户永远不能直接请求任何以此开头的视图。此外,您可以将模板名称作为第一个参数传递给@Html.EditorForModel(),因此它变为@Html.EditorForModel("_LatestContractNumber")
标签: asp.net-mvc