0

我在一个项目中使用 ASP.NET MVC 5,虽然我喜欢 MVC 的模型绑定功能,但我发现自己并没有经常使用它们,因为我使用的是 javascript MVVM 系统,而且我发现很难用模型粘合剂。

但我确实发现自己大量重复使用 HTML 代码来处理需要在多个地方复制的特定输入。

有什么方法可以使用@Html.EditorForetc 而不是指定一个属性,只需调用一个特定的模板来像一个小的内联片段引擎一样使用它?

更新

嘿伙计们,我接受了使用局部视图的建议,但我对其进行了一些更改。我想在 StackOverflow 上发布我的解决方案以获取反馈,因为我想知道这是否是一个好的做法,但现在我接受了答案。

4

2 回答 2

1

您可以为此使用部分视图。

于 2013-11-09T19:51:06.767 回答
1

您可以使用自己的用户界面。执行以下步骤:

转到 Views\Shared 并创建 [EditorTemplates] 文件夹。然后为每个类型或 UIHint 属性创建您自己的 *.cshtml 文件,例如为 int 类型创建 Int32.cshtml,如下所示:

@model int?

@{
    int i;
    if (!Model.HasValue)
    {
        i = 0;
    }
    else
    {
        i = Model.Value;
    }

    var htmlAttributes = new RouteValueDictionary();
    if (ViewBag.@class != null)
    {
        htmlAttributes.Add("class", "form-control " + ViewBag.@class);
    }
    else
    {
        htmlAttributes.Add("class", "form-control");
    }

    if (ViewBag.placeholder != null)
    {
        htmlAttributes.Add("placeholder", ViewBag.placeholder);
    }
}

<div class="form-group@(Html.ValidationErrorFor(m => m, " has-error"))">
    @Html.LabelFor(m => m, new { @class = "control-label" })
    <div class="controls">
        @Html.TextBox(
            "",
            ViewData.TemplateInfo.FormattedModelValue,
            htmlAttributes)
        @Html.ValidationMessageFor(m => m, null, new { @class = "help-block" })
    </div>
</div>
于 2013-12-05T20:24:15.837 回答