23

我目前正在为 ASP.NET MVC 中的网站构建管理后端。

在 ASP.NET MVC 应用程序中,我开始使用“EditorFor”辅助方法,如下所示:

<div id="content-edit" class="data-form">
    <p>
        <%= Html.LabelFor(c => c.Title) %>
        <%= Html.TextBoxFor(c => c.Title)%>
    </p>
    <p>
        <%= Html.LabelFor(c => c.Biography) %>
        <%= Html.EditorFor(c => c. Biography)%>
    </p>
</div>

在模型中,“传记”字段已被装饰为:[UIHelper("Html")]。

我有一个“Html”部分视图(在 Views/Shared/EditorTemplates 下):

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.XML.Linq.XElement>" %>

<textarea class="html">
    <%= Model.ToString() %>
</textarea>

现在我想将'textarea'的'ID'属性设置为字段的名称,如下所示:

<textarea id="Biography" class="html">
    ...
</textarea>

但是我看不到用当前设置的方法。

我能想到的就是创建一个包含“Value”属性和“ControlID”属性的“Html”ViewModel。

但是,如果我以此为基础而不是“System.XML.Linq.XElement”,它将不再与“EditorFor”辅助方法兼容,我必须手动完成所有操作。

有没有人遇到过类似的问题?

4

3 回答 3

37

您应该能够从视图的 ViewData.TemplateInfo.HtmlFieldPrefix 属性中提取所需的 ID。像这样:

<%@ Control Language="C#"
      Inherits="System.Web.Mvc.ViewUserControl<System.XML.Linq.XElement>" %>
<textarea id="<%= ViewData.TemplateInfo.HtmlFieldPrefix %>" class="html">
    <%= Model.ToString() %>
</textarea>

为了说明为什么这样做,这里是 TemplateHelpers.cs(MVC2 Preview 1 源)中为编辑器模板控件初始化 ViewData 的位置:

ViewDataDictionary viewData = new ViewDataDictionary(html.ViewDataContainer.ViewData) {
    Model = modelValue,
    TemplateInfo = new TemplateInfo {
        FormattedModelValue = formattedModelValue,
        ModelType = modelType,
        HtmlFieldPrefix = html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(expression),
        IsNullableValueType = (underlyingNullableType != null),
    }
};

在上面的调用中,“表达式”被初始化(在调用堆栈的上方),使用正在编辑的属性的名称。

顺便说一句,下面的@Sperling 捕获了我最初错过的一个细节:如果您正在使用(或可能使用)非默认值HtmlHelper.IdAttributeDotReplacement,那么您需要将HtmlPrefix属性中的点替换为HtmlHelper.IdAttributeDotReplacement.

于 2009-09-30T06:32:22.037 回答
4

一直在使用它来生成 id(带有模型前缀)。如果需要 name 属性,请跳过 .Replace() 部分。

<%=Html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(String.Empty).Replace(".", HtmlHelper.IdAttributeDotReplacement) %>
于 2009-09-30T13:33:03.387 回答
0

在我们的例子中,我们必须使用Html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldNamewithExpressionHelper.GetExpressionText

在剃须刀中是这样使用的:

           // hiddenFor was caching the value of this html input, and the value alone, nothing else on the page!
            Expression<Func<Web.ViewModels.ApiSettingsViewModel, int>> expression = (m => m.OrgApiLoginCredentials[i].OrgApiLoginId); 
        }
        <input type="hidden" value="@Model.OrgApiLoginCredentials[i].OrgApiLoginId" name="@Html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(expression))" class="data-org-api-login-id"/>
于 2014-12-08T14:39:56.360 回答