Lamloumi Afif
Lamloumi Afif

Reputation: 9081

Adding an extension method to HtmlHelper in asp.net mvc4 application

I would like to add an extension method for the html helper to customize a table, i add this method:

public static class HtmlElements
    {
        public static string Table(this HtmlHelper ht, string classe)
        {
            var table = new HtmlTable();
            table.Attributes.Add("class", classe);
            return table.InnerHtml;
        }

    }

When i'd like to use it like this

 @using(@Html.Table("table_data")){
}

i have an error which indicates that i have to convert a string to IDisposable type.

  1. What are the reasons of this error?
  2. How can i fix it?

Edit

the full view's code :

    using(var table = @Html.Table("table_data")){

        <tr>
             <th>Description</th>
            <th>Client</th>
            <th>Statut du client</th>
            <th>Etat de test</th>
            <th></th>
        </tr>

    for (int i = Model[2] - 5; i < Model[2]; i++)
    {
        if(i < Model[1].Count)
        {
        <tr style="font-size: 12px; padding:0px; ">
             <td>@Model[0][i].PDescription</td>
            <td>@Model[0][i].Nom_client</td>
             <td>@Model[0][i].Statut_client</td>
             <td style="color:red">@Model[1][i]</td>
             <td>
                @Model[0][i].Statut_client
             </td>
      </tr>
        }
    }
}

Upvotes: 1

Views: 2079

Answers (2)

Roy Dictus
Roy Dictus

Reputation: 33149

Your method returns a string, and when you use using in C#, that means you are insantiating an object that implements IDisposable, which string does not.

You are not doing anything with the string either. If you intend to build up an HtmlTable and do something with that, you must modify your code, for instance like so:

    public static HtmlTable Table(this HtmlHelper ht, string classe)
    {
        var table = new HtmlTable();
        table.Attributes.Add("class", classe);
        return table;
    }

and then you must use that in your code, like so:

@using(var table = @Html.Table("table_data")){
}

and within the brackets, you can now access the variable table.

Upvotes: 3

Ashley Medway
Ashley Medway

Reputation: 7309

public static class HtmlElements
{
    public static HtmlTable Table(this HtmlHelper ht, string classe)
    {
        var table = new HtmlTable();
        table.Attributes.Add("class", classe);
        return table;
    }
}

Upvotes: 1

Related Questions