问题
Suppose I have defined route like that,
context.MapRoute(
"Preview",
"/preview/{id}/{type}",
new { controller = "Preview", action = "Invoice", id = UrlParameter.Optional, type = UrlParameter.Optional }
);
I have controller with action Invoice
public ActionResult(int id, string type)
{
if (type == "someType")
{
// ...
}
else
{
// ..
}
}
I want to get rid of If-Else case inside the action. Is it possible to attribute action somehow, so ASP.MVC would distinguish between both, like:
Just a pseudocode tho show idea?
[HttpGet, ActionName("Action"), ForParameter("type", "someType")]
public ActionResult PreviewSomeType(int id) {}
[HttpGet, ActionName("Action"), ForParameter("type", "someType2")]
public ActionResult PreviewSomeType2(int id) {}
Is something like that possible in MVC2/3 ?
回答1:
Action method selector
What you need is an Action Method Selector that does exactly what you're describing and are used exactly for this purpose so that's not a kind of a workaround as it would be with a different routing definition or any other way. Custom action method selector attribute is the solution not a workaround.
I've written two blog posts that will get you started with action method selection in Asp.net MVC and these kind of attributes:
- Improving Asp.net MVC maintainability and RESTful conformance
this particular post shows an action method selector that removes action method code branches what you'd also like to accomplish; - Custom action method selector attributes in Asp.net MVC
explains action method selection in Asp.net MVC to understand the inner workings of it while also providing a selector that distinguishes normal vs. Ajax action methods for the same request;
回答2:
I think thats what routing is for. Just split your single route into two:
context.MapRoute(null, "preview/{id}/SomeType",
new {
controller = "Preview",
action = "Action1",
id = UrlParameter.Optional,
}
);
context.MapRoute(null, "preview/{id}/SomeOtherType",
new { controller = "Preview",
action = "Action2",
id = UrlParameter.Optional,
}
);
Or maybe more general, use the last segment as the action name:
context.MapRoute(null, "preview/{id}/{action}",
new { controller = "Preview",
id = UrlParameter.Optional,
}
);
But i think, optional segments have to appear at the end. So why don't you use the default routing schema
controller/action/id
?
来源:https://stackoverflow.com/questions/8600949/asp-net-mvc-2-actions-for-the-same-route