Ruben Serrate
Ruben Serrate

Reputation: 2783

How to pass an argument to the controller constructor? Is it the right thing to do?

I might not be doing this right because I'm new to this framework, I hope you can help ^^

As you can see in the code below, in every action I'm finding the table I want to update and then I call the method in the Table.

public class TableController : Controller
{
    private Lobby L;

    public TableController()
    {
        L = Lobby.Instance;

    }

    public ActionResult Index(uint id)
    {
        Table T = L.Tables[id];
        return View(T);
    }

    public ActionResult AddPlayer(byte pos, uint id)
    {
         Table T = L.Tables[id];

        ...
        T.AddPlayer(p, pos);
        ...
    }
 ...

}

But I've noticed that I'm doing the same thing in every method, so I though I could turn the table into an attribute so I don't need to find it for every action.

I would like to have something like this:

public class TableController : Controller
{
    private Lobby L;
    private  Table T;


    public TableController(uint tableId)
    {
        L = Lobby.Instance;
        T = L.Tables[tableId];
    }

    public ActionResult Index()
    {
        return View(T);
    }

    public ActionResult AddPlayer(byte pos)
    {
        ...
        T.AddPlayer(p, pos);
        ...
    }

Is there anything wrong in this approach?

If this is conceptually ok, how can I pass the table ID to my constructor? This is not working :(

        routes.MapRoute(
                "Table",
                "Table_{tableId}/{action}/",
                new { controller = "Table", action = "Index"}
            );

Upvotes: 2

Views: 2457

Answers (2)

haim770
haim770

Reputation: 49123

Typically, a Controller constructor is used to inject dependencies, not data. Moreover, at this stage, this.Request|Response|Session as well as other fundamental properties are still null.

Try this instead:

protected override void Initialize(RequestContext requestContext)
{
    var tableId = Convert.ToUInt32(requestContext.RouteData.GetRequiredString("tableId"));

    L = Lobby.Instance;
    T = L.Tables[tableId];

    base.Initialize(requestContext);
}

Upvotes: 5

freewill
freewill

Reputation: 1171

Pass the parameter to actions not to controller. Controller will be created each time a request happens. You can use static properties if you need them all time. Static properties can be accessed from any controller or action.

Upvotes: 1

Related Questions