Let us say I have 3 classes A, B and C. B and C inherit from A which contains the string field Name.
I have implemented the controllers As, Bs and Cs for ea开发者_高级运维ch class. I can list all instances of B and C in a view called Index produced by controller As.
The controllers Bs and Cs also have a method Details which spews out a view given the id for an instance of B and C respectively.
I am wondering about the cleanest way to produce action links for the details pages for B and C objects? I could use GetType() and produce the controller name based on this but this seems a bit cumbersome.
Hope this makes sense. Looking forward to hearing from you. Thanks.
Christian
You could define an extension method on your A class that will return the name of the controller:
public static class AExtensions
{
public static string GetControllerName(this A obj)
{
// put logic to determine type here
if( obj is B ) return "BController";
else if( obj is C ) return "CController";
else return "AController";
}
}
Then in your view you could have your link:
@Html.ActionLink("Details", "Details", obj.GetControllerName(), new { id= obj.Id })
This method sort of makes me feel dirty but it works I guess.
Somebody needs to make the decision about object type. All that remains is where you do it. If you only have a single list with all of the types in it you can split the list in the controller. Then recombine the types in the view.
foreach (var obj in AllObjs)
{
if (obj.GetType().Equals(typeof(B))
Model.AllBType.Add(obj);
else
Model.AllCType.Add(obj);
}
@foreach (var obj in Model.AllBType)
Html.ActionLink("Details", "Details", "BController", new { id = obj.Id });
@foreach (var obj in Model.AllCType)
Html.ActionLink("Details", "Details", "CController", new { id = obj.Id });
If you create the B and C objects or query for them individually by type why not just keep those results as independent lists in your model.
精彩评论