Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC app doesn't run with a generic method

I wanted to create a method in my Base controller that would take a list and return it as a SelectList. I wrote a method, and the site compiles, but I get this message:

Cannot call action method 'System.Collections.Generic.IEnumerable1[System.Web.Mvc.SelectListItem] GetSelectList[T](System.Collections.Generic.IEnumerable1[T], System.String, System.String, System.String, System.Object)' on controller 'PublicationSystem.Controllers.BaseController' because the action method is a generic method.
Parameter name: methodInfo

I'm wondering what I did wrong. Here's the code:

public partial class BaseController : Controller
{
    public IEnumerable<SelectListItem> GetSelectList<T>
    (
        IEnumerable<T> itemList, 
        string textField,
        string valueField,
        string defaultPrompt = "", 
        object defaultValue = null)
    {
        IEnumerable<SelectListItem> returnList = null;

        if (!string.IsNullOrEmpty(defaultPrompt))
        {
            returnList = Enumerable.Repeat(
                new SelectListItem { Value = (string)defaultValue, Text = defaultPrompt },
                count: 1);
        }

        var textProp = typeof (T).GetProperty(textField);
        var valueProp = typeof (T).GetProperty(valueField);

        returnList = returnList.Concat
            (itemList
                .Select(x =>
                    new SelectListItem
                    {
                        Value = Convert.ToString(valueProp.GetValue(x)),
                        Text = Convert.ToString(textProp.GetValue(x)),
                    }).Distinct().ToList());

        return returnList.ToList();
    }
}

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.LowercaseUrls = true;
        routes.MapMvcAttributeRoutes(); // Errors here
        //..
    }
}
like image 779
M Kenyon II Avatar asked Mar 04 '16 15:03

M Kenyon II


1 Answers

Your method is public in controller class. Asp.Net will see this method as an action method.

You can't use generic methods for action. Check this.

If you want to use this method on derived classes(your controllers). Make your method protected.

like image 81
Erkan Demirel Avatar answered Oct 05 '22 17:10

Erkan Demirel