0

If you take a look at this bootstrap documentation for formhelpers, I can use

<input type="text" class="form-control bfh-phone" data-format="+1 (ddd) ddd-dddd" placeholder="Cell or Home Phone" required>

to format a textbox when a user enters a phone number. I want to use an @Html.TextBoxFor or an @Html.EditorFor to do the same thing. How do I accomplish this in mvc? Here is what I have tried:

<input type="text" class="form-control bfh-phone" data-format="+1 (ddd) ddd-dddd" value="@Model.PhoneNumber" placeholder="Cell or Home Phone" required>

and

@Html.EditorFor(model => model.PhoneNumber, new { htmlAttributes = new { @class = "form-control bfh-phone", @placeholder = "Cell or Home Phone", @data-format="+1 (ddd) ddd-dddd" } })

both of which gives a object reference razor syntax error. How is this done?

1 Answer 1

3

When using the overload of EditorFor() that accepts object to add html attributes, you need to use an _ (underscore) character which will be translated to a - (hyphen) by the razor engine. Use data_format = "..", not data-format = ".."

@Html.EditorFor(m => m.PhoneNumber, new { htmlAttributes = 
    new { @class = "..", placeholder = "..", data_format="+1 (ddd) ddd-dddd" } })

Note also you do not need the leading @ character for placeholder or data_format (its only required for reserved words).

Sign up to request clarification or add additional context in comments.

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.