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?

3
  • 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) Commented Jun 21, 2016 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<strong, Object> from the TextBox? Commented Jun 22, 2016 at 8: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<string, object>() { { "@class", "form-control" }, { "type", "email" }, etc }; - you would be just writing extra code that more difficult to read. Commented Jun 22, 2016 at 8:45

0

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.