Christopher Johnson
Christopher Johnson

Reputation: 2629

create custom controls mvc3

Just starting to get the hang of MVC3 and want to start building out some custom controls that I can just drop into a view. Specifically I want to be able to drop in some html form controls that will automatically add some javascript for validation.

something like this is what I'd want:

@Html.VTextBox("MyTextBox","",new {@vType="PhoneNumber", @vMessage="You Must Enter a Phone Number" })

when the page is rendered, I'd want it to search for any custom elements I create then drop in the appropriate javascript to validate client side. I did something very similar to this with asp.net web forms for custom controls ie

<ucc:VTextBox ID="MyTextBox" runat="server" message="You must fill this in" />

just wondering if MVC3 offers the same extensibility. Any resources or advice you can provide would be greatly appreciated.

TIA

Upvotes: 0

Views: 1904

Answers (1)

xTRUMANx
xTRUMANx

Reputation: 1035

To start off with, you'll need to look into extension methods and more specifically, how to create extension methods for the HtmlHelper class so you could write code like the example you've shown above.

For the example you've shown above, you could write code like this:

public MvcHtmlString VTextBox(string name, object value, object htmlAttributes)
{
    StringBuilder html = new StringBuilder();

    // Build your html however you want
    // Here's a simple example that doesn't
    // take into account your validation needs
    html.AppendFormat("input type=\"text\" name=\"{0}\" value=\"{1}\" />", name, value);

    return MvcHtmlString(html.ToString());   
}

Then in your view you can use the example above like so:

@Html.VTextBox("MyTextBox","",new {@vType="PhoneNumber", @vMessage="You Must Enter a Phone Number" })

NOTE: You'll need to import the namespace the extension method is in to your view. Simplest method, put a @using ExtensionMethodNamespace at the top of your view. You can make the namespace automatically imported to all your views by fiddling with the web.config (and maybe the Global.asax).

ADDENDUM: Please note RPM1984's comment below where he advises to use TagBuilder in place of StringBuilder which is sound advice since this is the exact scenario TagBuilder was designed for. He also mentions strong typing the helper to the model which is also great advice.

Upvotes: 1

Related Questions