views:

35

answers:

1

Is it possible to assign an Lambda Expression (action?) to a property of my View Model, then use that expression in a Partial? What should the model's property type be? Psuedo Code:

View Model

public class MyModel
{
    public ????? MyAction {get;set;}
}

Controller

public ActionResult Index()
{
   var model = new MyModel();
   model.MyAction = ?????<MyController>(x => x.DoThis());

   return View(model);
}

public ActionResult DoThis()
{
   return View();
}

Partial.ascx, How would I assign the action to the ActionLink?

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MyModel>" %>

<%=Html.ActionLink<Controller>(x => x.DoThis())%>

I am using the strongly typed ActionLink from the Futures assembly.

A: 

Try this:

public class MyModel
{
    Expression<Action<MyController>> Action { get; set; }
}

...

model.Action = x => x.DoThis();

...

<%= Html.ActionLink( Model.Action ) %>
tvanfosson
That makes sense, but doesn't that hold true to the strongly typed ActionLink in general? Aren't they including that in the 2.0?
mxmissile
Ok. I think I misread what you were trying to do. I thought you were trying to run some code in the controller to get back the function that is used to generate the link. I'll update.
tvanfosson
What if I don't know the Controller type? Can MyController be generic?
mxmissile
Sorry for expanding, but what if DoThis has arguments with values that are not known until runtime? ex: DoThis(int id);
mxmissile
You could use an interface or base controller but you'd only be able to access the methods in the interface or that are defined by the base class. I think that the variables will be captured by the lambda and will have their final values when the expression is evaluated. Use a temp variable if the values will change after the action is assigned.
tvanfosson
Thanks I got it working using a base class.
mxmissile