Please help me to correct my ASP.NET MVC Route Map.
I've got a menu item with an ActionLink:
<li>#Html.ActionLink("Articles", "List", "Article")</li>
On the Home page it looks like:
localhost/Article which is OK.
But on the concrete Article page with URL localhost/Article/List/11 my menu link is the same:
localhost/Article/List/11
But I need localhost/Article
My route map code is as follows:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Article",
url: "Article/{action}/{id}",
defaults: new { controller = "Article", action = "List", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
Here is controller code:
public ActionResult List(int? id)
{
ArticlesDataManager artMgr = new ArticlesDataManager();
ArticleViewModel art = new ArticleViewModel();
art.Articles = artMgr.GetLastArticles();
art.Article = (id == null) ? artMgr.GetLast() : artMgr.GetArticle((int)id);
ViewData.Model = art;
return View();
}
my problem was solved by changing my route map:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "ArticleByFirst",
url: "Article/{action}/",
defaults: new { controller = "Article", action = "List" }
);
routes.MapRoute(
name: "ArticleById",
url: "Article/List/{id}",
defaults: new { controller = "Article", action = "List", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
And my menu-link looks like: <li>Articles</li>
And my item-link is: <li>#item.Name</li>
It's not good, that I can't choose name of Route Map in ActionLink.
I guess your current querystrings items are being added to your action link. To avoid this problem, Use this overload and try to explicitly pass null as RouteValues and see what changes it brings.
public static MvcHtmlString ActionLink(
this HtmlHelper htmlHelper,
string linkText,
string actionName,
string controllerName,
RouteValueDictionary routeValues,
IDictionary<string, Object> htmlAttributes
)
So your code can be re-written as
<li>#Html.ActionLink("Articles", "List", "Article",
new RouteValueDictionary { },null)</li>
You can also try this version also
Articles
Related
i would like to create rest api but I have problem with routing.
This url is ok: localhost/project/controller/action/id, but i would like this url localhost/project/controller/id too.
For example: localhost/project/article/5: ArticleController.Get(int id)
This is my code:
Project controller
[HttpGet]
[Route("project/{id}")]
public JsonResult Get(int id)
{
}
Route config:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Api",
url: "{controller}/{id}",
defaults: new { id = UrlParameter.Optional }
);
}
When i call url localhost/project/article/5, error message is A public action method '5' was not found on controller 'ArticleController'.
Where is problem? Thanks
You can use attribute routing
Example:
[HttpGet]
[Route("project/{controller}/{action}/{id}")]
public JsonResult Get(int id)
{
}
OR
Default Route Table
Example:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Api",
url: "project/{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
As Per your Requirement, your Routing is:
[HttpGet]
[Route("project/article/{id:int}")]
public JsonResult Get(int id)
{
}
OR
routes.MapRoute(
name: "Api",
url: "project/article/{id}",
defaults: new { controller = "ArticleController", action = "Get", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "MyRoute",
url: "{Product}/{name}-{id}",
defaults: new { controller = "Home", action = "Product", name = UrlParameter.Optional , id = UrlParameter.Optional }
);
my routemap and i want my url in product action be like = http://localhost:13804/Wares/Product/name-id
but now is like =
http://localhost:13804/Wares/Product/4?name=name
When defining a route pattern the token { and } are used to indicate a parameter of the action method. Since you do not have a parameter called Product in your action method, there is no point in having {Product} in the route template.
Since your want url like yourSiteName/Ware/Product/name-id where name and id are dynamic parameter values, you should add the static part (/Ware/Product/) to the route template.
This should work.
routes.MapRoute(
name: "MyRoute",
url: "Ware/Product/{name}-{id}",
defaults: new { controller = "Ware", action = "Product",
name = UrlParameter.Optional, id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Assuming your Product action method accepts these two params
public class WareController : Controller
{
public ActionResult Product(string name, int id)
{
return Content("received name : " + name +",id:"+ id);
}
}
You can generate the urls with the above pattern using the Html.ActionLink helper now
#Html.ActionLink("test", "Product", "Ware", new { id = 55, name = "some" }, null)
I know its late but you can use built-in Attribute Routing in MVC5. Hope it helps someone else. You don't need to use
routes.MapRoute(
name: "MyRoute",
url: "{Product}/{name}-{id}",
defaults: new { controller = "Home", action = "Product", name = UrlParameter.Optional , id = UrlParameter.Optional }
);
Instead you can use the method below.
First enable attribute routing in RouteConfig.cs
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
}
Then in WaresController
[Route("Wares/Product/{name}/{id}")]
public ActionResult Product(string name,int id)
{
return View();
}
Then to navigate write code like this in View.cshtml file
Navigate
After following above steps your URL will look like
http://localhost:13804/Wares/Product/productname/5
On the Index.cshtml view of EuroController i have an ActionLink that i want to use the "IndexByYear" action of Euro controller:
#Html.ActionLink("Year 2006", "IndexByYear","Euro", new { id = "", year = 2006 }, null)
But the problem is that it goes to the Index() method, even though it's everything set on RouteConfig:
routes.MapRoute(
name: "Default",
url: "{controller}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Euro",
url: "{controller}/{year}/{id}",
defaults: new { controller = "Euro", action = "IndexByYear", year = DateTime.Now.Year, id = UrlParameter.Optional }
);
Here's the EuroController:
public ActionResult Index(int? id)
{
...
}
public ActionResult IndexByYear(int? id, int year)
{
...
}
Also this don't work, as it also goes to Index() method:
#Html.RouteLink("Ano 2006","Euro",new { id = "", year = 2006 },null)
If i manually navigate to domain/Euro/2016/1, then it uses the correct route. Seems like with no parameters it goes through the Default route.
My question is, why does the ActionLink don't use the IndexByYear as specified, or the RouteLink use the specified default (Euro) route?
If you want just the EuroController to have a "special" routing, you would want to do something like:
routes.MapRoute(
name: "Euro",
url: "euro/{year}/{id}",
defaults: new { controller = "Euro", action = "IndexByYear", year = DateTime.Now.Year, id = UrlParameter.Optional }
);
routes.MapRoute(
name: "DefaultNoController",
url: "{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
constraints: new { isMethodInHomeController = new RootRouteConstraint<Controllers.HomeController>() }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Where the constraint is defined like so:
public class RootRouteConstraint<T> : IRouteConstraint
{
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
var rootMethodNames = typeof(T).GetMethods().Select(x => x.Name.ToLower());
return rootMethodNames.Contains(values["action"].ToString().ToLower());
}
}
This will match
domain/euro/1 to the Index action on EuroController
domain/euro/2008/1 to the IndexByYear action on EuroController
domain/ to the Index action on HomeController
domain/about to the About action on HomeController
domain/someothercontroller to the Index action on whatever other controllers you define
You may want to read https://msdn.microsoft.com/en-us/library/cc668201.aspx and https://www.asp.net/mvc/overview/older-versions-1/controllers-and-routing/creating-a-custom-route-constraint-cs
I have a controller named Registration and an action method in it as the following:
public JsonResult GetReqs(GridSettings gridSettings, int rt)
{
...//whatever
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
So I added a route and now my RouteConfig.cs is like this:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "RegReq",
url: "{Registration}/{GetReqs}/{rt}",
defaults: new { controller = "Registration", action = "GetReqs", rt = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
However I can't access the rt parameter and the action method GetReqs isn't called(I set a breakpoint on it but nothing happened). Where is the mistake?
Edit: Link example I tried : ~/Registration/GetReqs/1
I think you need to remove the brackets in your first route:
routes.MapRoute(
name: "RegReq",
url: "Registration/GetReqs/{rt}",
defaults: new { controller = "Registration", action = "GetReqs",
rt = UrlParameter.Optional }
);
The default route has {controller} to tell MVC to use the string in that section of the url as the controller name. You know the controller, so you just need to match the specific string.
I am trying to show user details at the following url :
www.website.com/users/yasser
where the last entry yasser is the username I have tried a couple of routes but it just does nt work.
My User controller is as shown below.
public class UserController : Controller
{
public ActionResult Index(string username)
{
var model = _service.GetUserDetails(username);
return View(model);
}
}
I have reffered this and couple of other links, but I really could not figure out how it worked.
Can some one help me out on this. Thanks
Edit :
My current route config is below
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
Routes executes from top to the bottom:
routes.MapRoute("UserProfile",
"Users/{username}",
new { controller = "User", action = "Index", username = string.Empty }
);
routes.MapRoute("Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional}
);