我希望有一个部分视图可以自动解析Controller-Action-Id标签
因此,当用户访问“/ Classroom / Detail / A1”URL时,导航元素将显示:
我的课堂>信息> A1课堂
“/教师/详细内容/史密斯” 将导致
我的老师>信息>史密斯太太
考虑以下控制器:
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";
}
}
}
另一个控制器
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 "?";
}
}
}
此控制器将最终字符串结果呈现为PartialView:
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
});
}
//...
}
}
我使用Castle Windsor来解析我的控制器。从IoC容器中检索控制器实例是否可以接受(我的控制器有LifestylePerWebRequest)?
有更好的方法吗?