Search code examples
asp.net-mvchtmlhtml-helper

Creating a color inputtype through Htmlhelper.editorfor() (MVC)


I have the following part of a form created using htmlhelper:

    <div class="form-group">
        @Html.LabelFor(model => model.ColorCode, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.ColorCode, new {htmlAttributes = new { @class = "form-control" } })
            <!--<input type="color" class="form-control"/>-->
            @Html.ValidationMessageFor(model => model.ColorCode, "", new {@class = "text-danger"})
        </div>
    </div>

The datatype of ColorCode is string, so by default it just creates a normal textbox. What I want is to have the input behave as a color selector. The commented html is essentially what I want it to create (+ whatever attributes are needed to connect it to the form, if applicable. I'm not a HTML expert). Is there a way to do this? I can't find any information on it through my searches.


Solution

  • You can try something like this:

    @Html.TextBoxFor(model => model.ColorCode, new {@class="form-control", type="color"})
    

    The EditorFor will use Editor Templates to generate the html output. To use that you have to define an Editor template for that particular property type, but since that's a string it's a bit generic.

    Also @Stephen Muecke pointed it out in the comment.