简体   繁体   中英

Writing html extension that accept list of Lambda expressions for accessing Properties

I want to write a html extension that generate HTML table;

public static class HtmlHelpers
{
    public static IHtmlString DisplayPropreties<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, params Expression<Func<TModel, TProperty>>[] expressions)
    {
        // some code here
    }
}

The problem is when I want to call the method from the view:

@Html.DisplayPropreties(model => m.Id, model => m.Property1, model => m.Property2)

Im getting error:

The type argument for method 'HtmlHelpers.DisplayPropreties(HtmlHelper, params Expression>[])' cannot be inferred with current usage. Try specifying the type arguments explicitly

I did not touch c# for some while (3+y), and I don't fully understand what I need to do.

Demo Online

you can use Json.Net 's Jsonconvert Serialize collection obeject then

DeserializeObject collection to DataTable then

call ConvertDataTableToHTML method get HtmlTable from the DataTable object.

public static class HtmlHelpers
{
    public static string ToHtmlTable(this HashSet<dynamic> obj)
    {
        return ToHtmlTableConverter(obj);
    }

    public static string ToHtmlTable(this ICollection obj) {
        return ToHtmlTableConverter(obj);
    }

    public static string ToHtmlTable(this System.Data.DataTable obj)
    {
        return ConvertDataTableToHTML(obj);
    }

    private static string ToHtmlTableConverter( object obj  )  
    {
        var jsonStr = JsonConvert.SerializeObject(obj);
        var data = JsonConvert.DeserializeObject<System.Data.DataTable>(jsonStr);
        var html = ConvertDataTableToHTML(data);
        return html;
    }

    private static string ConvertDataTableToHTML(System.Data.DataTable dt)
    {
        var html = new StringBuilder("<table>");

        //header
        html.Append("<thead><tr>");
        for (int i = 0; i < dt.Columns.Count; i++)
            html.Append("<th>" + dt.Columns[i].ColumnName + "</th>");
        html.Append("</tr></thead>");

        //body
        html.Append("<tbody>");
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            html.Append("<tr>");
            for (int j = 0; j < dt.Columns.Count; j++)
                html.Append("<td>" + dt.Rows[i][j].ToString() + "</td>");
            html.Append( "</tr>");
        }

        html.Append("</tbody>");
        html.Append("</table>");
        return html.ToString();
    }
}

It's exactly what the error says. You need to specify the type arguments as they can't be inferred, eg:

HtmlHelpers.GenerateTable<Foo, Bar>(model => m.Id, model => m.Property1, model => m.Property2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM