MVC controller action overload
Can I do something similar to this in a way that doesn't throw an error:
public class AdsController : Controller
{
AdsRepository repo = new AdsRepository();
public ActionResult Details(string id)
{
AdSlots adslot = new AdSlots();
Enum.TryParse(id, true, out adslot);
return Content(repo.GetInvocationCode(adslot开发者_StackOverflow中文版, Global.SiteInfo.ID));
}
[ChildActionOnly]
public ActionResult Details(AdSlots slot)
{
return Content(repo.GetInvocationCode(slot, Global.SiteInfo.ID));
}
}
The point is that I want to have a way of accessing the resource through /ads/details/leaderboard as a url in the browser, but also in master pages using:
<% Html.RenderAction("Details", "Ads", new {slot = AdSlots.Leaderboard }); %>
I just think that is cleaner than:
<% Html.RenderAction("Details", "Ads", new {slot = "Leaderboard" }); %>
If I do as above and call the url /ads/details/leaderboard I get this error:
The current request for action 'Details' on controller type 'AdsController' is ambiguous between the following action methods.. etc
I didn't think I would get that error as I have given the attribute [ChildActionOnly] to the other action. I would think then it was obvious for the system that if I access it through the browser I would only have one option, not so apparently.
Maybe not the nicest, but
<% Html.RenderAction("Details", "Ads", new {id = AdSlots.Leaderboard.ToString() }); %>
should always result in the first action... And since the problem being that MVC calls a ToString() on your enum ANYWAY, so you could just leave out the second controller action alltogether, and then your problem might go away... Parsing an enum is not that expensive...
The ChildActionOnlyAttribute
only enforces that the action is called as part of a child request through Html.Action
and Html.RenderAction
in your view. This attribute is not considered when MVC attempts to match a method to the incoming route call.
精彩评论