无法在MVC3中使用编辑器模板

时间:2011-08-18 15:43:03

标签: asp.net-mvc

我正在将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

2 个答案:

答案 0 :(得分:0)

首先,您使用EditorForModel类型(您的视图的模型)调用IEnumerable<ITOF.Models.LatestContractNumber>,但您应该使用ITOF.Models.LatestContractNumber(这是您的模型)来调用它模板期望看到/得到)。你需要一个foreach

foreach(ITOF.Models.LatestContractNumber number in Model) {
    @Html.EditorForModel(number)
}

其次,不是100%肯定,但EditorTemplates应该位于Views文件夹下的Shared文件夹中。所以~/Views/Shared/EditorTemplates/并且应该以类名LatestContractNumber.cshtml命名。

HTH

答案 1 :(得分:-1)

这个问题原来是一个红鲱鱼。真正的问题是迁移到MVC并开始使用_前缀部分视图时,编辑器模板的名称无效。 感谢Russ Cam提出的正确问题让我得到了答案。