如何为我的模型创建Html.EditorFor以节省时间?

时间:2011-08-16 20:24:24

标签: asp.net-mvc asp.net-mvc-3 editorfor

我目前只有我的专辑类的创建视图:

@model MvcApplication1.Models.AlbumViewModel

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>AlbumViewModel</legend>

        <p> 
            @Html.LabelFor(model => model.GenreId) 
            @Html.DropDownListFor(x => x.GenreId, new SelectList(Model.Genres, "GenreId", "name"))
        </p>

        <p> 
            @Html.LabelFor(model => model.ArtistId) 
            @Html.DropDownListFor(x => x.ArtistId, new SelectList(Model.Artists, "ArtistId", "Name"))
        </p>


        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

我被告知使用EditorFor进行创建和编辑以便将来节省时间是合乎惯常的。

所以我的观点最终会像这样:

@model MvcApplication1.Models.AlbumViewModel

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

@Html.EditorForModel

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

这是对的吗?如何以及在何处在我的解决方案中声明并写下来?

编辑:

我在主帐户/注册视图中有这个:

@model Models.RegisterViewModel

@{
    ViewBag.Title = "Register";
}

<h2>Register</h2>

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>RegisterViewModel</legend>

        @Html.EditorFor(model => model.RegisterModel)
        @Html.EditorFor(model => model.Cities)
        @Html.EditorFor(model => model.Countries)
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset> 
}

在我的EditorTemplate中:

enter image description here

@model Fooer.WebUI.Models.RegisterModel

THIS IS A TEST.

但它根本不会呈现虚拟文本。它渲染模型的默认控件。

2 个答案:

答案 0 :(得分:2)

您可以将部分文件添加为~/Views/Shared/EditorTemplates/下的文件。

Brad Wilson关于Custom object templates主题的博客文章提供了您需要的所有信息。

答案 1 :(得分:-1)

将您的观点更改为:

@model MvcApplication1.Models.AlbumViewModel

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

@Html.EditorForModel()

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

这将输出模型的所有属性。关于其使用的好帖子here