0

I would like to design a model with some way of specifying a Controller Action to be used for searching. I do not want to specify the action's url as a string because I do not want the app to compile if that action does not exist.

From what I can tell, it seems like I should specify a property of type System.Web.Mvc.ActionDescriptor like so:

public class myModel {
    public string id { get; set; }
    ...
    public ActionDescriptor search_action { get; set; }
}

From this SO post I see how to get iterate through all actions on all controllers but I'm having trouble instantiating an ActionDescriptor to set the property.

I was hoping to be able to do some variation of this:

myModel m = new myModel();
m.search_action = 
    (ActionDescriptor)new myNamespace.Controllers.myController().myAction;

but didn't get anywhere.

Am I missing something? How do you specify a Controller Action as a property of a model? Is this even possible?

Community
  • 1
  • 1
Greg
  • 8,574
  • 21
  • 67
  • 109

2 Answers2

0

You can declare a Func delegate property with the respective Action specific type arguments in your model which you will set with your Action.

public class myModel {
    public string id { get; set; }
    //Specify your specific Action's type arguments here
    public Func<,> search_action { get; set; }
}
Yair Nevet
  • 12,725
  • 14
  • 66
  • 108
0

First, I'm forced to ask why you need to stored the action itself as part of the model. It seems like the wrong approach; but again I lack the context and the rationale as to why you are trying to do this.

If only want to have the compile safety that the action exists, you might be better off creating an expression method based on the type of the controller and extracting the string action name from it (like this answers suggest).

If in the other hand, you actually want to able to execute this action from the model (even after understanding how bad of an idea this is) using an ActionDescriptor (which only stored information about the action) or a Func<,> (which only stores the IL, not the name, the context or the controller), will only get you half way.

And so again, I ask, why exactly you need to do this?

Community
  • 1
  • 1
rae1
  • 6,066
  • 4
  • 27
  • 48