genxgeek
genxgeek

Reputation: 13357

Html Helper to create a resuable func in mvc3 razor view?

I have the following block(s) of code that is copy and pasted about 5 different times within a razor view. It basically displays a table for the same model just with different data.

How can I re-write it as an html helper or lambda func so that I can reuse it for n different models that are passed into the view?

  // Example for Model.A and Model.B 

  var cCols = new[] { "val1", "val2"};

    // Display the data for A
   <div class="group-property">
    <div class="group-label">Title A</div>        
        <table class="collection-table">
        <thead>
        <tr class="collection-head">@foreach (var col in cCols) {<th scope="col">@col</th>}</tr>
         </thead>
         <tbody>
            @foreach (var item in Model.A)
            {
                <td>@item.val1</td>
                <td>@item.val2</td>
            }
         </tbody>
         </table>
    </div>

   // Display the data for B
   <div class="group-property">
    <div class="group-label">Title B</div>        
        <table class="collection-table">
        <thead>
        <tr class="collection-head">@foreach (var col in cCols) {<th scope="col">@col</th>}</tr>
         </thead>
         <tbody>
            @foreach (var item in Model.B)
            {
                <td>@item.val1</td>
                <td>@item.val2</td>
            }
         </tbody>
         </table>
    </div>

Upvotes: 0

Views: 404

Answers (2)

DMulligan
DMulligan

Reputation: 9073

I'm not sure what you've tried, but to make it an helper function you just need to take the pieces that vary and make them parameters to the function:

@helper MyHelperFunction(string title, IEnumerable<ItemClass> items)
{
var cCols = new[] { "val1", "val2"};

<div class="group-property">
<div class="group-label">@title</div>        
    <table class="collection-table">
    <thead>
    <tr class="collection-head">@foreach (var col in cCols) {<th scope="col">@col</th>}</tr>
     </thead>
     <tbody>
        @foreach (var item in items)
        {
            <td>@item.val1</td>
            <td>@item.val2</td>
        }
     </tbody>
     </table>
</div>
}

@MyHelperFunction("Title A", Model.A)
@MyHelperFunction("Title B", Model.B)

Upvotes: 1

Andrei Neagu
Andrei Neagu

Reputation: 896

I don't know if I get it right, but why not use @Html.Partial ?

Andrei Neagu

Upvotes: 2

Related Questions