如何覆盖 @Html.LabelFor 模板?
我有一个简单的字段表单
<div class="field fade-label">
@Html.LabelFor(model => model.Register.UserName)
@Html.TextBoxFor(model => model.Register.UserName)
</div>
,结果是:
<div class="field fade-label">
<label for="Register_UserName">Username (used to identify all services, from 4 to 30 chars)</label>
<input type="text" value="" name="Register.UserName" id="Register_UserName">
</div>
但我希望 LabelFor
代码在里面附加一个 ,这样我最终可以得到:
<label for="Register_UserName">
<span>Username (used to identify all services, from 4 to 30 chars)</span>
</label>
如何我这样做?
所有示例 使用EditorTemplates
,但这是一个LabelFor
。
I have a simple field form
<div class="field fade-label">
@Html.LabelFor(model => model.Register.UserName)
@Html.TextBoxFor(model => model.Register.UserName)
</div>
and this results in:
<div class="field fade-label">
<label for="Register_UserName">Username (used to identify all services, from 4 to 30 chars)</label>
<input type="text" value="" name="Register.UserName" id="Register_UserName">
</div>
but I want that LabelFor
code append a <span>
inside so I can end up having:
<label for="Register_UserName">
<span>Username (used to identify all services, from 4 to 30 chars)</span>
</label>
How can I do this?
All examples use EditorTemplates
but this is a LabelFor
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以通过创建自己的 HTML 帮助器来完成此操作。
http://www.asp.net/mvc/tutorials/creating -custom-html-helpers-cs
可以查看LabelFor<>的代码通过下载 ASP.Net MVC 的源并将其修改为自定义帮助程序。
答案由balexandre添加
You'd do this by creating your own HTML helper.
http://www.asp.net/mvc/tutorials/creating-custom-html-helpers-cs
You can view the code for LabelFor<> by downloading the source for ASP.Net MVC and modify that as a custom helper.
Answer added by balexandre
我扩展了 balealexandre 的答案,并添加了指定 HTML 以包含标签文本之前和之后的功能。我添加了一堆方法重载和注释。我希望这对大家有帮助!
还从这里获取信息:使用 Html 助手的 Html 内部标签
I expanded upon balealexandre's answer and added in the ability to specify HTML to include both before and after your label text. I added a bunch of method overloads and comments. I hope this helps folks!
Also snagged information from here: Html inside label using Html helper
LabelFor 是一个扩展方法(静态),因此不能被重写。您需要创建自己的 Html Helper Extension 方法来实现您的需求。
LabelFor is an extension method (static) and therefore cannot be overridden. You'd need to create your own Html Helper Extension method to achieve what you require.