Pass generic model to controller

2

My project follows the following template:

InmyControllerIhavethefollowing:

InoticedthatIcouldbeusingthisActionResultdynamically.Myviewistyped.

Iwouldliketoknowifthereisawaytopassthetypeofmyviewpromodelorsomemeansofdynamicallyreceivingmodelinmycontroller.Beingintheexample,mymodel"Homogenous Group".

In summary, my intention is to pass the name of model and somehow, create something that returns the model filtered by name in my ActionResult , as in the case of System.Object

"Example" of what I want:

        var Nome = "GrupoHomogeneoEF";
        var bdModel = new (Nome)(contexto);
    
asked by anonymous 10.09.2015 / 16:42

2 answers

4

I still do not understand what you want to do, but View accepts by default the following:

@model dynamic

That is, you can always spend anything.

Of course this has consequences. You need to check if the Model property exists:

@if (Model.GetType().GetProperty("propriedade") != null) { ... }

I would also make a generic Controller :

public abstract class Controller<T> : System.Web.Mvc.Controller
    where T: class, new() { ... }

And Action GrupoHomogeneo :

public virtual ActionResult GrupoHomogeneo(T objeto, FormCollection collection) { ... }

Or, you can define a common ancestor:

public abstract class ModelAncestralComum { ... }

And restrict the generic Controller :

public abstract class Controller<T> : System.Web.Mvc.Controller
    where T: ModelAncestralComum, new() { ... }
    
23.09.2015 / 20:19
2

Well, from what I understand you want to make your controller generic and have a generic action, but the view will continue to be specialized.

Below is a pretty straightforward suggestion to your point, but would have other improvements that could be made, you could read this article for more information.

public class GenericController<TObjeto, TRepositorio> : Controller
    where TObjeto : ObjetoBase, new()
    where TRepositorio : RepositorioEFBase, new()
{
    [HttpPost]
    public virtual ActionResult AcaoGenerica(TObjeto objeto, FormCollection collection)
    {
        var repositorio = new RepositorioEFBase(contexto);
        ...
        return RedirectToAction(collection["ReturnView"], objeto);
    }
}

public class GrupoHomogeneoController : GenericController<GrupoHomogeneo, GrupoHomogeneoRepositorioEF>
{
}

public abstract class ObjetoBase
{
    public int ID {get; set;}
}

public class GrupoHomogeneo : ObjetoBase
{
    public string Campo1 {get; set;}
}

public abstract class RepositorioEFBase<TObjeto>
    where TObjeto : ObjetoBase, new()
{
    private DbContext _contexto;
    public RepositorioEFBase(DbContext contexto)
    {
            _contexto = contexto;
    }

    //utilize esse DbSet para os seus metodos genericos
    internal IDbSet<TObjeto> DbSet { get { return _contexto.Set<TObjeto>(); } }

    //metodos genericos do repositorio
}

public class GrupoHomogeneoRepositorioEF : RepositorioEFBase<GrupoHomogeneo>
{

}
    
23.09.2015 / 21:49