ASP.NET GetFullHtmlFieldId 未返回有效 ID
在MVC2模板中,我通常使用this.ViewData.TemplateInfo.GetFullHtmlFieldId(fieldName) 生成 html 元素的 id 字段。这在大多数情况下都有效。
然而,此方法实际上并不返回 有效的 id 字段,它只是在 fieldName
前面加上 ViewData.TemplateInfo.HtmlFieldPrefix
,这在渲染具有 []
的集合时给我带来了问题HtmlFieldPrefix。
我已经在我发现需要的地方手动将这些字符转换为 _
,但这似乎不优雅(重复代码),有没有人找到正确生成 id 字段的好方法?
In MVC2 template, I normally use this.ViewData.TemplateInfo.GetFullHtmlFieldId(fieldName)
to generate the id field of an html element. This has worked in most of the cases.
However this method does not actually return valid id field, it merely prefix fieldName
with ViewData.TemplateInfo.HtmlFieldPrefix
, this is causing problems for me when rendering collections which has []
in the HtmlFieldPrefix.
I have been manually converting those characters to _
where I find the need, but this seems to be not elegant (repeated code), has anyone found a good way to generate id field properly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您能更具体地说明您遇到的问题类型吗?
例如,有一种优雅的方法 使用 提供验证支持。虽然它不使用模板,但部分视图仍然保持干燥。
虽然 ids 不一致 - 名称没问题,但我遇到的唯一问题是使用 jquery.infieldlabel 时,标签的 for 属性(由 LabelFor 帮助器内的 GetFullHtmlFieldId 生成)与相应 TextBoxFor 输入的 id 不匹配。因此,我创建了 LabelForCollectionItem 辅助方法,该方法仅使用与 TextBox 相同的 id 生成方法 -
TagBuilder.GenerateId(fullName)
也许代码不符合您的需求,但希望它能帮助别人,因为我在第一个寻找解决我的问题的方法中发现了你的问题。
Can you be more specific about the kind of problems do you have?
For example, there is an elegant approach to editing variable length list with validation support provided. While it doesn't use templates still remains DRY with partial views.
While the ids are inconsistent - the names are OK and only problem I encountered is that using jquery.infieldlabel it appeared that label's for attribute (generated by GetFullHtmlFieldId inside LabelFor helper) didn't match id of the appropriate TextBoxFor input. So I created LabelForCollectionItem helper method that just uses the same method for id generation as the TextBox -
TagBuilder.GenerateId(fullName)
Maybe the code doesn't correspond to your need but hope it will help somebody since I found your question among the first searching for solution to my problem.