BrianLegg
BrianLegg

Reputation: 1700

How to create MVC user control using html helper

I have a control that will be used over and over so I am trying to create a user control for it. I've been following along in the following article but something seems to be missing from his explanation. I've written the static class like this:

    public static class SingleSelectionControl
{
    public static MvcHtmlString SingleSelection(this HtmlHelper htmlHelper, string cssClass, string modelField) //case-field & caseName
    {
        StringBuilder builder = new StringBuilder();

        builder.Append("<div class='wizard-field'>");
        builder.Append("<textarea id='" + cssClass + "' class='wizard-textbox-field' ng-model='model." + modelField + "Value'></textarea>");
        builder.Append("<textarea id='" + cssClass + "-page' class='wizard-hidden' ng-model='model." + modelField + "Page'></textarea>");
        builder.Append("<ul class='wizard-horizontal-button-list'>");
        builder.Append("<li>");
        builder.Append("<input type='button' class='add button' onclick='getHighlightedText('#" + cssClass + "')' />");
        builder.Append("<input type='button' class='search button' onclick='setPage($('#" + cssClass + "-page').val()); setSearchText('#" + cssClass + "')' />");
        builder.Append("</li>");
        builder.Append("</ul>");
        builder.Append("</div>");

        return MvcHtmlString.Create(builder.ToString());
    }
}

And I am attempting to call SingleSelection from my view using the following code:

<div class="formA" id="_FormA">
    <div id="@Model.Order" style="display: none;">@Model.TemplateName</div>

    @using (Html.BeginForm())
    {
        <fieldset>
            <legend>Initial Filing</legend>

            <div class="wizard-label">
                <span>Case Name:</span>
            </div>
            @Html.SingleSelection("case-field", "caseName");

However, as I expected, @Html.SingleSelection is not recognized.

This post is similar but also doesn't explain how the view and the static method are connected.

How do I "register" this method so that I can call it from my views via @Html.? Thanks!

Upvotes: 0

Views: 429

Answers (1)

user3559349
user3559349

Reputation:

Either include a @using yourNamespace in the view, or better add it to the web.config file so its available in all views

<pages>
    <namespaces>
        <add namespace="System.Web.Helpers" />
        <add namespace="System.Web.Mvc" />
        ....
        <add namespace="yourAssembly" />

Upvotes: 1

Related Questions