Provide data annotation for placeholder attr for textbox in MVC
Asked Answered
R

3

10

Is there a way to have a data annotation for what should be in placeholder attr on a textbox in an MVC view?

Example:

In my ViewModel.cs, something like:

[Placeholder="First name"]
public string FirstName { get; set; }

In my view:

@this.Html.TextBoxFor(m => m.FirstName)

If that could render this:

<input type="text" placeholder="First name" ... />

Is this possible? Thanks!

Rheumatism answered 31/1, 2012 at 19:52 Comment(0)
H
11

try

@this.Html.TextBoxFor(m => m.FirstName, new{placeholder="First name"})

Ah, not in the model.

You can define your own custome attribute http://blogs.msdn.com/b/aspnetue/archive/2010/02/24/attributes-and-asp-net-mvc.aspx. I think you will need a custom html helper to generate the html.

Highspirited answered 1/2, 2012 at 10:12 Comment(2)
this is great! do you know which attribute I would need to inherit from? the example in your link inherits from ActionFilterAttributeRheumatism
the example has a list of attribute classes, pick the one that is closest to what you want to do. Or use inherit from System.Attribute for a clean(er) start.Highspirited
A
3

I realize this has been asked a long, long time ago but the Display attribute with the Prompt argument is probably what you want here.

    [Display(Prompt = "Enter the country (default US)")]
    public string Country { get; set; }
Aleurone answered 28/5, 2021 at 9:5 Comment(0)
F
0

I don't think so, but you could write your own custom helper and attribute to do it. http://www.aspnetwiki.com/page:creating-custom-html-helpers

Fewer answered 31/1, 2012 at 20:3 Comment(2)
thanks for the link! unfortunately, I don't see any examples where I can have [Placeholder="First name"] above the property in my view model. Instead, there are examples for this.Html.TextboxFor(m => m.FirstName, "Placeholder text here"), which would defeat the purpose because I want this hard-coded text to be with the view model, not in the view.Rheumatism
I know, you would need to roll your own helper and attribute. Here, BuildStarted's answer shows how he created a custom attribute, #7419164. You custom helper could then read your custom attribute.Fewer

© 2022 - 2024 — McMap. All rights reserved.