开发者

ideas on building a strongly typed class to manage URLS for asp.net mvc

I want a strongly typed url class 开发者_StackOverflowthat i will reference whenever I need a url for any links, redirecting, etc.

I don't like:

RedirectToActoin("Action", "Controller");

A site with 50+ views means any naming change is going to break allot of things.

I also want a user frienly api so I can do:

MyUrls.ControllnerName.ActionName

How can I achieve this? is it possible?


Have a look at the T4MVC project (part of MvcContrib). It gives you strongly typed helpers for actions, controllers and views.


Excerpt from the project documentation:

T4MVC is a T4 template for ASP.NET MVC apps that creates strongly typed helpers that eliminate the use of literal strings when referring the controllers, actions and views. It helps make your MVC code much more maintainable, and gives you intellisense where you normally would not have any.

Instead of this:

<% Html.RenderPartial("DinnerForm"); %>

You can write this:

<% Html.RenderPartial(MVC.Dinners.Views.DinnerForm); %>


I actually prefer an approach inspired by the MVCContrib folks, which is to utilize a custom method on the controller that uses a Lambda Expression to specify where you are wanting to go.

protected internal RedirectToRouteResult RedirectToAction<TController>(Expression<Func<TController, object>> action) where TController: Controller
{
    var controllerName = typeof(TController).Name.Replace("Controller", string.Empty);
    var actionName = ((MethodCallExpression)action.Body).Method.Name;
    return RedirectToAction(actionName, controllerName);
}

And using it would look like this:

return RedirectToAction<HomeController>(h => h.Index());

With this approach you get the advantages of having easy to read statements and when you refactor your action names these statements get updated as well (or cause build errors if you don't use the rename refactor).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜