MVC Helper with Generic List

3

I'm creating a Helper in my Asp.Net MVC 5 project, and I'd like to get a generic list as a parameter, but the following code snippet does not work:

@helper MeuHelper(string param1, int param2, List<T> param3)
{
   // Sequência de código
}

The error generated is:

  

The type or namespace name 'T' could not be found (are you missing a   using directive or an assembly reference?)


After all, is it possible to have my helper receive in%% of a generic list?

    
asked by anonymous 28.12.2016 / 20:28

1 answer

4

No can directly cause the @helper " has generic features (at least at the moment ), of course there are other means that may not match what you need but an example of how work with information :

@helper MeuHelper(string param1, int param2, System.Collections.IEnumerable param3)
{
    <div>@(param1)</div>
    <div>@(param2)</div>
    var items = param3.GetEnumerator();
    while (items.MoveNext())
    {
            <div>@(items.Current)</div>
    }
}


@functions
{
    public HelperResult MeuHelperFunction<T>(string param1, int param2, List<T> param3)
    {
        return MeuHelper(param1, param2, param3);
    }
}


@MeuHelperFunction("Nome", 1, new int[] { 1, 2, 2, 4, 5 }.ToList())

@helper is called by a function ( @MeuHelperFunction ) that has a IEnumerable parameter that will accept this list of any kind, is a reasonable way. Reinforcing @helper does not accept faceplates Generic is for simple and point coding.

The best way to work with this is to do a Extension method that quietly accepts generic parameters , example:

using System.Web.Mvc;
using System.Collections.Generic;
namespace WebApplication1
{
    public static class MyHelperExtension
    {
        public static MvcHtmlString MeuHelper<T>(this HtmlHelper _html,
                                                 string param1, 
                                                 int param2, 
                                                 List<T> param3)
        {
            return MvcHtmlString.Empty;
        }
    }
}

Calling on View :

@Html.MeuHelper("Nome", 1, new int[] { 1, 2, 2, 4, 5 }.ToList())

In version Core ( MVC6 ) for example, has been removed @ helper and was introduced #.

References:

28.12.2016 / 20:56