views:

187

answers:

1

Hello everybody,

I have ascx partial view with html-layout like that

<%=Html.ActionLink<PersonController>(x => x.Publications(param1, param2, ... )) %>

My ascx is pretty big & I'd like to reuse it, changing controller/method in Html.ActionLink with another controller/method. Method of another controller has the same signature as PersonController.Publications. Please, suggest me the best way how to make controller/method configurable for my layout.

Thank you in advance

A: 

The easiest way would be to have the controller name and action name as strings on your model. Then you could use the non strongly typed overload of actionlink. Something like this:

<%=Html.ActionLink(Model.Action, Model.Controller, new { param1 = 1, param2 = 2 })%>

And use it like this:

<%Html.RenderPartial("PartialName", new PartialModel{Controller = "Person", Action = "Publications"})%>

If you want to use the strongly typed version you can do something like this:

//Model for your partial view
public class PartialModel<TController> where TController : Controller
{
    public Func<int, int, Expression<Action<TController>>> GetLinkAction { get; set; }
}

//Render the action link in your partial
<%=Html.ActionLink(Model.GetLinkAction(1, 2))%>

//Render the partialview in any page
<%Html.RenderPartial("PartialName", new PartialModel<PersonController> { GetLinkAction = (param1, param2) => x => x.Publications(param1, param2) })%>

You will of course have to adjust this for the parameters that you have. The nice thing about the strongly typed way is that the methods doesn't have to have the exact same signature and parameter names.

Mattias Jakobsson
Wonderfull :) Thank you very much !
Andrew Florko