你对这类问题有更具体的了解吗?
例如,有一个editing variable length list的优雅方法,validation support提供。尽管它不使用模板,但仍然保留DRY与部分视图。
虽然id不一致,但名称还是可以的,只有我遇到的问题是,使用jquery.infieldlabel时,标签的for属性(由LabelForHelper中的GetFullHtmlFieldId生成)与适当的TextBoxFor输入的id不匹配。所以我创建只是用同样的方法进行ID生成的文本框LabelForCollectionItem助手方法 - TagBuilder.GenerateId(fullName)
也许代码不符合您的需要,但希望这将帮助别人,因为我发现第一个搜索中你的问题解决我的问题。
public static class LabelExtensions
{
/// <summary>
/// Generates Label with "for" attribute corresponding to the id rendered by input (e.g. TextBoxFor),
/// for the case when input is a collection item (full name contains []).
/// GetFullHtmlFieldId works incorrect inside Html.BeginCollectionItem due to brackets presense.
/// This method copies TextBox's id generation.
/// </summary>
public static MvcHtmlString LabelForCollectionItem<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression,
string labelText = null, object htmlAttributes = null) where TModel : class
{
var tag = new TagBuilder("label");
tag.MergeAttributes(new RouteValueDictionary(htmlAttributes)); // to convert an object into an IDictionary
// set inner text
string htmlFieldName = ExpressionHelper.GetExpressionText(expression);
string innerText = labelText ?? GetDefaultLabelText(html, expression, htmlFieldName);
if (string.IsNullOrEmpty(innerText))
{
return MvcHtmlString.Empty;
}
tag.SetInnerText(innerText);
// set for attribute
string forId = GenerateTextBoxId(tag, html, htmlFieldName);
tag.Attributes.Add("for", forId);
return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal));
}
/// <summary>
/// Extracted from System.Web.Mvc.Html.InputExtensions
/// </summary>
private static string GenerateTextBoxId<TModel>(TagBuilder tagBuilder, HtmlHelper<TModel> html, string htmlFieldName)
{
string fullName = html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName);
tagBuilder.GenerateId(fullName);
string forId = tagBuilder.Attributes["id"];
tagBuilder.Attributes.Remove("id");
return forId;
}
/// <summary>
/// Extracted from System.Web.Mvc.Html.LabelExtensions
/// </summary>
private static string GetDefaultLabelText<TModel, TValue>(HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>> expression, string htmlFieldName)
{
var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
string labelText = metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last();
return labelText;
}
}
所以在你的方法中,如果htmlFieldName包含方括号会发生什么?例如“Users [0]” – 2010-05-19 21:37:28
Html.LabelForCollectionItem(x => x.Users [0] .Name)返回
这是一个有趣的方式,帮助我上来为我们的具体情况提供解决方案。谢谢! (我会投票你的答案,如果你可以编辑它 - 所以绕过愚蠢的计算器规则) – 2010-05-20 20:08:46