0

I'm familiar with using the Html.TextBox method to render a textbox. Suppose that I want to write a method that is similar to Html.TextBox, but takes a single additional string attribute called Abc which renders a TextBox just like one rendered by TextBox, but adds an attribute called data-abc with the value specified by Abc.

What is a good way to do this?

2 Answers 2

2

Add the attribute data_abc to the optional parameters and it will add it as data-abc.

@Html.TextBox("Name", "Default Value", new { data_abc = "data" });

Good luck!

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

Comments

0

Here's what I came up with that seems to work:

    public static MvcHtmlString MyTextBox<T>(this HtmlHelper helper, string name, string value, object htmlAttributes, string Abc)
    {
        IDictionary<string, object> myHtmlAttributes = new RouteValueDictionary(htmlAttributes);

        myHtmlAttributes.Add("data-abc", Abc);

        return helper.TextBox(propertyName, value, myHtmlAttributes);
    }   

1 Comment

While correct, it depends on if you want to do this routinely or with different attribute names. The framework allows for data attributes to be added by default, so I'd be tempted to just use those.

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.