1

I have an MVC form with a few fields and I am trying to add some HTML attributes to the fields such as input type and also a CSS class. I've been looking at ASP.NET MVC HTML helper methods for new HTML5 input types along with other Stack Overflow threads to get it working.

Visual Studio tells me that type and class do not exist in the current context. I've found the problem to be the dictionary on the fields as if I remove the dictionary reference, it seems to work.

<div class="col-lg-12">
            @Html.LabelFor(x => x.EmailAddress)<span class="required">*</span>
            @Html.TextBoxFor(x => x.EmailAddress, new Dictionary<string, Object> { { @class = "form-control", type = "email", autocomplete = "email", "required", "" } })
            <small class="error">Please provide your email address.</small>
            @Html.ValidationMessageFor(x => x.EmailAddress)
        </div>

Full confession, I'm pretty new to MVC and I found the form example on a blog as an Umbraco form example as the site is running Umbraco. If you need to see the View Model or the Controller please let me know and I can post those too.

I'm guessing here that using a dictionary doesn't play nice with adding HTML attributes and if that's the case, what can I do to get around it?

Community
  • 1
  • 1
richardjgreen
  • 69
  • 1
  • 10
  • 2
    Its just `@Html.TextBoxFor(x => x.EmailAddress, new { @class = "form-control", type = "email", autocomplete = "email" })` (and do not use `required` - add a `[Required]` attribute to your property) –  Jun 21 '16 at 23:16
  • Thanks for the reply Stephen. So just to ask a question if I may? What is the impact, if any, of dropping the new Dictionary from the TextBox? – richardjgreen Jun 22 '16 at 08:37
  • Nothing really. Both get converted internally to a `RouteValueDictionary`. But if your really wanted to use `Dictionary` then its needs to be `new Dictionary() { { "@class", "form-control" }, { "type", "email" }, etc };` - you would be just writing extra code that more difficult to read. –  Jun 22 '16 at 08:45

0 Answers0