1

I have an @html.textBox and I am woundering if I can define Label inside rather then using separate @html.label tag ...

many thanks

Textbox

  @Html.TextBox("Input_AvailableMark_Element", null, new { id = @item.ElementID + "_AM", @class = "ElementAvailableMarks k-grid-input k-textbox_3" })

Label

    @Html.Label("AvailableMark", null, new {@class ="inputTextLabel_Custom_1" })                                        
2
  • What do you mean "define label inside"? Your question isn't clear. Please explain clearly what you're trying to achieve - maybe some example output would help. Commented Mar 11, 2014 at 12:37
  • @AntP, I think he wants to write just one line of code instead of two (one for the label and another for the textbox). @Html.EditorFor would work... Commented Mar 11, 2014 at 12:43

2 Answers 2

3

The only way I can think of to do that is with usage of placeholder attribute:

@Html.TextBoxFor(model => model.SomeProperty, new { placeholder = Model.SomeProperty })

I'm assuming you are using DataAnnotations for your models. So for example if you want the Display attribute value to be in your placeholder then you need to write this extension method to fetch data annotation DISPLAY attribute:

public static class GetAttributeExtension
{
    public static string GetDisplayName<TModel, TValue>(this TModel model, Expression<Func<TModel, TValue>> expression)
    {
        return GetDisplayName(expression);
    }

    public static string GetDisplayName<TModel, TValue>(Expression<Func<TModel, TValue>> expression)
    {
        var propertyName = ((MemberExpression)expression.Body).Member.Name;
        return typeof(TModel).GetAttribute<DisplayAttribute>(propertyName).Name;
    }
}

And then you can do something like this:

@Html.TextBoxFor(model => model.SomeProperty, new { placeholder = Model.GetDisplayName(m => m.SomeProperty) })
Sign up to request clarification or add additional context in comments.

Comments

1

Depending on what browsers you need to support, the easiest option is as @Marko suggests, add the placeholder attribute. http://www.w3schools.com/tags/att_input_placeholder.asp

However, if you need to support non-HTML5 compliant browsers, this will not work. There are some javascript libraries that will do this behavior for you http://www.wduffy.co.uk/jLabel/

I have used jLabel before and it works pretty well, but is not without its problems.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.