반응형
@ 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
코드가 <span>
내부에 추가되어 결국 다음을 가질 수 있습니다.
<label for="Register_UserName">
<span>Username (used to identify all services, from 4 to 30 chars)</span>
</label>
어떻게 할 수 있습니까?
모든 예제가 사용 EditorTemplates
되지만 이것은 LabelFor
.
고유 한 HTML 도우미를 만들어이를 수행 할 수 있습니다.
http://www.asp.net/mvc/tutorials/creating-custom-html-helpers-cs
ASP.Net MVC의 소스를 다운로드하여 LabelFor <>에 대한 코드를보고이를 사용자 지정 도우미로 수정할 수 있습니다.
의해 추가 된 답변 balexandre
public static class LabelExtensions
{
public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, object htmlAttributes)
{
return LabelFor(html, expression, new RouteValueDictionary(htmlAttributes));
}
public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, IDictionary<string, object> htmlAttributes)
{
ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
string htmlFieldName = ExpressionHelper.GetExpressionText(expression);
string labelText = metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last();
if (String.IsNullOrEmpty(labelText))
{
return MvcHtmlString.Empty;
}
TagBuilder tag = new TagBuilder("label");
tag.MergeAttributes(htmlAttributes);
tag.Attributes.Add("for", html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName));
TagBuilder span = new TagBuilder("span");
span.SetInnerText(labelText);
// assign <span> to <label> inner html
tag.InnerHtml = span.ToString(TagRenderMode.Normal);
return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal));
}
}
LabelFor는 확장 메서드 (정적)이므로 재정의 할 수 없습니다. 필요한 것을 달성하려면 고유 한 Html Helper Extension 메서드를 만들어야합니다.
나는 balealexandre의 답변을 확장하고 레이블 텍스트 앞뒤에 모두 포함하도록 HTML을 지정하는 기능을 추가했습니다. 메서드 오버로드와 주석을 많이 추가했습니다. 나는 이것이 사람들을 돕기를 바랍니다!
또한 여기에서 정보를 포착했습니다 : Html 도우미를 사용하는 Html 내부 레이블
namespace System.Web.Mvc.Html
{
public static class LabelExtensions
{
/// <summary>Creates a Label with custom Html before the label text. Only starting Html is provided.</summary>
/// <param name="startHtml">Html to preempt the label text.</param>
/// <returns>MVC Html for the Label</returns>
public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, Func<object, HelperResult> startHtml)
{
return LabelFor(html, expression, startHtml, null, new RouteValueDictionary("new {}"));
}
/// <summary>Creates a Label with custom Html before the label text. Starting Html and a single Html attribute is provided.</summary>
/// <param name="startHtml">Html to preempt the label text.</param>
/// <param name="htmlAttributes">A single Html attribute to include.</param>
/// <returns>MVC Html for the Label</returns>
public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, Func<object, HelperResult> startHtml, object htmlAttributes)
{
return LabelFor(html, expression, startHtml, null, new RouteValueDictionary(htmlAttributes));
}
/// <summary>Creates a Label with custom Html before the label text. Starting Html and a collection of Html attributes are provided.</summary>
/// <param name="startHtml">Html to preempt the label text.</param>
/// <param name="htmlAttributes">A collection of Html attributes to include.</param>
/// <returns>MVC Html for the Label</returns>
public static MvcHtmlString LabelFor<TModel, TProperty>(this HtmlHelper<TModel> html, Expression<Func<TModel, TProperty>> expression, Func<object, HelperResult> startHtml, IDictionary<string, object> htmlAttributes)
{
return LabelFor(html, expression, startHtml, null, htmlAttributes);
}
/// <summary>Creates a Label with custom Html before and after the label text. Starting Html and ending Html are provided.</summary>
/// <param name="startHtml">Html to preempt the label text.</param>
/// <param name="endHtml">Html to follow the label text.</param>
/// <returns>MVC Html for the Label</returns>
public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, Func<object, HelperResult> startHtml, Func<object, HelperResult> endHtml)
{
return LabelFor(html, expression, startHtml, endHtml, new RouteValueDictionary("new {}"));
}
/// <summary>Creates a Label with custom Html before and after the label text. Starting Html, ending Html, and a single Html attribute are provided.</summary>
/// <param name="startHtml">Html to preempt the label text.</param>
/// <param name="endHtml">Html to follow the label text.</param>
/// <param name="htmlAttributes">A single Html attribute to include.</param>
/// <returns>MVC Html for the Label</returns>
public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, Func<object, HelperResult> startHtml, Func<object, HelperResult> endHtml, object htmlAttributes)
{
return LabelFor(html, expression, startHtml, endHtml, new RouteValueDictionary(htmlAttributes));
}
/// <summary>Creates a Label with custom Html before and after the label text. Starting Html, ending Html, and a collection of Html attributes are provided.</summary>
/// <param name="startHtml">Html to preempt the label text.</param>
/// <param name="endHtml">Html to follow the label text.</param>
/// <param name="htmlAttributes">A collection of Html attributes to include.</param>
/// <returns>MVC Html for the Label</returns>
public static MvcHtmlString LabelFor<TModel, TProperty>(this HtmlHelper<TModel> html, Expression<Func<TModel, TProperty>> expression, Func<object, HelperResult> startHtml, Func<object, HelperResult> endHtml, IDictionary<string, object> htmlAttributes)
{
ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
string htmlFieldName = ExpressionHelper.GetExpressionText(expression);
//Use the DisplayName or PropertyName for the metadata if available. Otherwise default to the htmlFieldName provided by the user.
string labelText = metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last();
if (String.IsNullOrEmpty(labelText))
{
return MvcHtmlString.Empty;
}
//Create the new label.
TagBuilder tag = new TagBuilder("label");
//Add the specified Html attributes
tag.MergeAttributes(htmlAttributes);
//Specify what property the label is tied to.
tag.Attributes.Add("for", html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName));
//Run through the various iterations of null starting or ending Html text.
if (startHtml == null && endHtml == null) tag.InnerHtml = labelText;
else if (startHtml != null && endHtml == null) tag.InnerHtml = string.Format("{0}{1}", startHtml(null).ToHtmlString(), labelText);
else if (startHtml == null && endHtml != null) tag.InnerHtml = string.Format("{0}{1}", labelText, endHtml(null).ToHtmlString());
else tag.InnerHtml = string.Format("{0}{1}{2}", startHtml(null).ToHtmlString(), labelText, endHtml(null).ToHtmlString());
return MvcHtmlString.Create(tag.ToString());
}
}
}
참고 URL : https://stackoverflow.com/questions/5196290/how-can-i-override-the-html-labelfor-template
반응형
'Programing' 카테고리의 다른 글
HTML에서 컨테이너 div를 사용해야하는 이유는 무엇입니까? (0) | 2020.11.21 |
---|---|
SSL 인증서가 서버 IP 주소에 바인딩되어 있습니까? (0) | 2020.11.21 |
GCC는 루프 내에서 증가하는 사용되지 않는 변수를 어떻게 최적화합니까? (0) | 2020.11.21 |
옵션을 동적으로 변경할 때 IE 선택 문제를 해결하는 방법 (0) | 2020.11.21 |
소스 파일 'Properties \ AssemblyInfo.cs'를 찾을 수 없습니다. (0) | 2020.11.20 |