MVC Helper with List Energy

Asked

Viewed 151 times

3

I am creating a Helper in my Asp.Net MVC 5 project, and would like to receive as a parameter a generic list, 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, it is possible to make my helper receive on param3 a generic list?

1 answer

4


Not it is directly possible to make the @helper have generic vestments (at least until the moment), of course there are other means that may not match what you need but, an example of how you could work with the 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())

the @helper is called by a function (@MeuHelperFunction) that has a parameter IEnumerable that will accept this list of any kind, is a reasonable way. Reinforcing the @helper does not accept generic parameters is for punctual and simple encoding.


The best way to work with this is to make a extension method who 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 in the View:

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

In the version Core (MVC6) for example, was removed @helper and was introduced Taghelpers.

References:

  • 1

    Thank you very much for the reply! Actually worked here the first proposal only with the IEnumerable in place of my List<T>. You didn’t even have to create anything in functions.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.