RedirectToAction Alternative

I am using ASP.NET MVC 3.

I have an assistant class as follows:

public static string NewsList(this UrlHelper helper) { return helper.Action("List", "News"); } 

And in my controller code, I use it like this:

 return RedirectToAction(Url.NewsList()); 

So, after redirecting, the link looks like this:

 ../News/News/List 

Is there an alternative to RedirectToAction? Is there a better way I need to implement my helper method NewsList?

+4
source share
1 answer

You really don't need an assistant:

 return RedirectToAction("List", "News"); 

or if you want to avoid hard coding:

 public static object NewsList(this UrlHelper helper) { return new { action = "List", controller = "News" }; } 

and then:

 return RedirectToRoute(Url.NewsList()); 

or another opportunity to use MVCContrib , which allows you to write the following (personally, which I love and use):

 return this.RedirectToAction<NewsController>(x => x.List()); 

or another option is to use T4 templates .

So, you decide and play.


UPDATE:

 public static class ControllerExtensions { public static RedirectToRouteResult RedirectToNewsList(this Controller controller) { return controller.RedirectToAction<NewsController>(x => x.List()); } } 

and then:

 public ActionResult Foo() { return this.RedirectToNewsList(); } 

UPDATE 2:

Unit test example for the NewsList extension NewsList :

 [TestMethod] public void NewsList_Should_Construct_Route_Values_For_The_List_Action_On_The_News_Controller() { // act var actual = UrlExtensions.NewsList(null); // assert var routes = new RouteValueDictionary(actual); Assert.AreEqual("List", routes["action"]); Assert.AreEqual("News", routes["controller"]); } 
+7
source

Source: https://habr.com/ru/post/1337953/


All Articles