1

I would like to have a partial view that would automatically resolve Controller-Action-Id labels

So when user accesses "/Classroom/Detail/A1" URL, Navigation element will display:

My classrooms > Info > Classroom A1

"/Teachers/Detail/Smith" will result in

My teachers > Info > Mrs.Smith

Consider following controllers:

public class TestController : Controller
{
    public TestController(IDependency dependency)
    {
    }
    public ActionResult Detail(string id)
    {
        //...
        return View();
    }
    public string ResolveLabelForId(string id)
    {
        switch (id)
        {
            case "A1":
                return "Classroom A1";
            case "B2":
                return "Classroom B2";
            default:
                return "Classroom";
        }
    }
}

Another controller

public class TeacherController : Controller
{
    public TeacherController(IDependency dependency)
    {
    }
    public ActionResult Detail(string id)
    {
        //...
        return View();
    }
    public string ResolveLabelForId(string id)
    {
        switch (id)
        {
            case "Smith":
                return "Mrs. Smith";
            case "Jackson":
                return "Mr. Jackson";
            default:
                return "?";
        }
    }
}

The final string result is rendered as a PartialView by this controller:

public class PartialViewController : Controller
{
    private readonly IDictionary<Tuple<string,string>, Tuple<string,string>> Labels = new
            Dictionary<Tuple<string, string>, Tuple<string,string>> 
        {
            {new Tuple<string, string>("Classroom","Detail"), new Tuple<string, string>("My classrooms","Info")},
            {new Tuple<string, string>("Teacher","Detail"), new Tuple<string, string>("My teachers","Info")}
        };
    public ActionResult NavigationBar()
    {
        var routeValues = ControllerContext.ParentActionViewContext.RouteData.Values.Values.ToArray();
        string controller = (string)routeValues[0];
        string action = (string)routeValues[1];
        string id = (string)routeValues[2];
        Tuple<string, string> result;
        if (Labels.TryGetValue(new Tuple<string, string>(controller, action), out result))
        {
            return PartialView(new string[]
                {
                    result.Item1,
                    result.Item2,
                    id//??Resolve ID label
                });
        }
        //...
    }
}

I use Castle Windsor to resolve my Controllers. Would it be acceptable to retrieve the controller instance from the IoC container (My controllers have LifestylePerWebRequest)?

Is there a better approach?

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.