![](/img/trans.png)
[英]ASP.NET MVC: How to call custom Html Helper from a controller method?
[英]How to give custom name to HTML helper Label in ASP.NET MVC?
如何为 HTML 助手 label 提供自定义名称? 以及如何对其应用样式?
我希望 label output 是这样的:
在HTML
我们可以这样实现:
<label class="Color">Degree Title<span class="Text-danger">*</span><label>
但是如何通过 ASP.NET MVC 中的 HTML 辅助方法 Labelfor 来实现这一点?
我尝试了这段代码,但它在浏览器上显示相同的文本,我在这里用引号Degree Level <span class='Text-danger'>*</span>
写:
@Html.LabelFor(model => model.Level, "Degree Level <span class='Text-danger'>*</span> ", htmlAttributes: new { @class = "control-label"})
如何修改它?
您可以尝试使用一些自定义 HTML 助手:
public static class LabelExtensions
{
public static MvcHtmlString LabelForCustom<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, string labelText, object htmlAttributes)
{
var text = html.LabelFor(expression, labelText, htmlAttributes);
return new MvcHtmlString("<div>" + text + "<span class=\"Text-danger\">*</span>" + "</div>");
}
}
并从.cshtml
调用它:
@Html.LabelForCustom(model => model.Level, "Degree Level ", htmlAttributes: new { @class = "control-label" })
并且有必要在.cshtml
顶部添加@using
:
@using namespace_where_LabelExtensions_class_is_defined
笔记:
如果您想在<label>
中包含<span>
标签,则需要在删除var text = html.LabelFor(expression, labelText, htmlAttributes);
线。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.