Alon Gubkin
Alon Gubkin

Reputation: 57129

Generics in ASP.NET MVC Controller Methods

In ASP.NET MVC 3, how can I do something like that?

public JsonResult Create<T>(T field) where T : Field
{
    ...
}

Thanks.

Upvotes: 1

Views: 385

Answers (2)

ADIMO
ADIMO

Reputation: 1117

public class SpecificField : Field
{
    ...
}

public class SpecificController : BaseController<SpecificField>
{
    ....
}

public class BaseController<T> : Controller where T : Field
{
    public JsonResult Create( T field )
    {
        ....
    }
}

Upvotes: 0

DanielB
DanielB

Reputation: 20230

You can have a gerneric Controller.

public abstract class BaseFieldController<T> : Controller where T : Field
{
    public virtual JsonResult Create(T field)
    {
        ...
    }
}

Then extend from it

public class FieldController : BaseFieldController<Field>
{

}

Upvotes: 1

Related Questions