michael
michael

Reputation: 585

how to add content to html.label in javascript asp.net mvc

I have a label as <%= Html.Label("");%> i want to add content to label at runtime, unfortunately it doesn't take any other parameter to create id property for it. can't i create id property for it just similar to asp:label

thanks,

michaeld

Upvotes: 0

Views: 2398

Answers (2)

Christophe Geers
Christophe Geers

Reputation: 8952

If you want to keep using HtmlHelper functions you can always create your own extension methods.

For example:

public static class LabelHelper
{
    private static string HtmlAttributes(object htmlAttributes)
    {
        var builder = new StringBuilder();
        foreach (PropertyDescriptor descriptor in 
            TypeDescriptor.GetProperties(htmlAttributes))
        {
            builder.AppendFormat(" {0}=\"{1}\" ", descriptor.Name, 
                descriptor.GetValue(htmlAttributes));
        }
        return builder.ToString();
    }

    public static MvcHtmlString MyLabel(this HtmlHelper htmlHelper, 
        string labelText, object htmlAttributes)
    {
        var attributes = HtmlAttributes(htmlAttributes);
        return MvcHtmlString.Create(
            String.Format("<label for=\"{0}\" {1}>{0}</label", 
            labelText, attributes.Trim()));
    }
}

Then you can add a label to a view in the following manner:

<%: Html.MyLabel("Hello, World!", new { @id = "myLabel" })%>

The generated HTML is:

<label for="Hello, World!" id="myLabel">Hello, World!</label>

For MVC 3 such a helper function is already available:

http://msdn.microsoft.com/en-us/library/gg538318(v=VS.99).aspx

Upvotes: 0

Mika T&#228;htinen
Mika T&#228;htinen

Reputation: 983

No need to use the HtmlHelper functions always and everywhere if they don't fit your need. They're just supposed to make your life easier, not harder. Use good ole HTML here:

<label id="id_for_label"></label>

Upvotes: 2

Related Questions