Scott Silvi
Scott Silvi

Reputation: 3109

How to create html helper in mvc

The code I'm currently using is this:

@Html.LabelFor(model => model.MaxExecutions)
<div class="input-append">
    @Html.TextBoxFor(model => model.MaxExecutions, new { @class = "input-xxlarge", placeholder="Enter Max Executions" })
    <span class="add-on"><a href='#' class='title' rel='tooltip' title="Help Title" data-content="Help Message">?</a></span>
    @Html.ValidationMessageFor(model => model.MaxExecutions)
</div>

I repeat this over & over in my code. I'd love to pass this off to an HtmlHelper. The type of Model I pass in can change, and I'd like to have the Display attribute available from the model (or I'd just generate an htmlstring).

Upvotes: 0

Views: 893

Answers (1)

Dennis Rongo
Dennis Rongo

Reputation: 4611

You can implement an extension method or a helper (static) class but there's times where I like the declarative version (CSHTML). Either way works and can be passed around from controller, etc.

~/App_Code/Blah.cshtml

@helper ExecuteHelper() {
   @Html.LabelFor(model => model.MaxExecutions)
   <div class="input-append">
       @Html.TextBoxFor(model => model.MaxExecutions, new { @class = "input-xxlarge",    placeholder="Enter Max Executions" })
    <span class="add-on"><a href='#' class='title' rel='tooltip' title="Help Title" data-content="Help Message">?</a></span>
   @Html.ValidationMessageFor(model => model.MaxExecutions)
   </div>
}

Then call it in view like:

@Blah.ExecuteHelper()

I've noticed the amount of HTML you have it in which is why I opted for the @helper syntax solution. Here's an article by Scott Guthrie that outlines this MVC feature: Article

Upvotes: 1

Related Questions