我无法弄清楚如何在 Html.LabelFor 中使用 @class,因此我使用在 SO 上找到的代码更新了 Html.Label 的扩展助手。
我的 LabelExtension.cs 文件具有以下类:
public static class LabelExtensions
{
public static string Label(this HtmlHelper helper,
string labelFor,
string value,
object htmlAttributes)
{
TagBuilder labelBuilder = new TagBuilder("label");
if (!string.IsNullOrEmpty(labelFor))
{
labelBuilder.Attributes.Add("for", labelFor);
}
labelBuilder.MergeAttributes(new RouteValueDictionary(htmlAttributes));
labelBuilder.SetInnerText(value);
return labelBuilder.ToString(TagRenderMode.Normal);
}
}
我最初在 MVC2 .aspx 页面中使用了以下内容(我将其转换为 .cshtml):
<% Html.BeginForm(); %> <%= Html.Label("txt_name_udq", "Your First Name (required):",
new {
@class
= "mylabelstyle" } )%>
<br />
<%= Html.TextBox("txt_name_udq", null, new {
@class
= "myinputstyle" } )%>
<br />
<%= Html.Label("txt_email_udq", "Your E-Mail Address (required):", new {
@class
= "mylabelstyle" } )%>
<br />
<%= Html.TextBox("txt_email_udq", null, new {
@class
= "myinputstyle" })%>
<br />
<% Html.EndForm(); %>
这在 MVC2 中渲染得非常好(为了简洁,我省略了 using 等)。然而,今天在转换为 .cshtml (使用 _layout.cshtml)时,我发现 Html.Label 没有渲染,而是输出源代码。这是代码:
@section QuoteForm
{
<div class="entryfull">
<div class="entryfull_box">
<div class="entryfull_text">
<h2>
Quote Request
</h2>
<ul class="ul-check">
<li>Free</li>
<li>Confidential</li>
<li>Anonymous</li>
<li>No Obligation</li>
</ul>
@using (Html.BeginForm())
{
@Html.Label("txt_name_udq", "Your First Name (required):", new { @class = "mylabelstyle" })
<br />
@Html.TextBox("txt_name_udq", null, new { @class = "myinputstyle" })
<br />
@Html.Label("txt_email_udq", "Your E-Mail Address (required):", new { @class = "mylabelstyle" })
<br />
@Html.TextBox("txt_email_udq", null, new { @class = "myinputstyle" })
<br />
}
</div>
</div>
</div>
}
以上只是简单的内容,并非最终产品。我只是想让它先渲染。注意:1)我尝试了 Html.BeginForm 的各种迭代; 2)我什至将它包含在 .尽管如此,它仍然没有“工作”。
这是您在浏览器上看到的标签(在浏览器中输出的源),位于文本框(呈现)的正上方:
<label class="mylabelstyle" for="txt_name_udq">Your First Name (required):</label>;
如果您“查看源代码”,您将看到以下内容:
<label class="mylabelstyle" for="txt_name_udq">Your First Name (required):</label>;
这与@section有关吗?或者我正在尝试使用 MVC2 的扩展?
提前感谢您的任何想法/建议。
编辑:这是我在评论中引用的适用于我的情况的代码。感谢您的帮助。
public static MvcHtmlString Label(this HtmlHelper htmlHelper, string labelFor, string value,
object htmlAttributes)
{
var tagBuilder = new TagBuilder("label");
tagBuilder.MergeAttributes(new RouteValueDictionary(htmlAttributes));
tagBuilder.MergeAttribute("for", labelFor.Replace(".", tagBuilder.IdAttributeDotReplacement), true);
tagBuilder.SetInnerText(value);
return MvcHtmlString.Create(tagBuilder.ToString(TagRenderMode.Normal));
}
最佳答案
那是因为你的助手返回一个字符串,并且默认编码。您的助手应该返回 MvcHtmlString 并将返回语句更改为
return new MvcHtmlString(labelBuilder.ToString(TagRenderMode.Normal));
关于asp.net-mvc - Razor:无法在 @Section 中渲染 Html.Label 帮助程序(仅输出源),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5516166/