Asp.Net MVC 4 routing and link generation - asp.net-mvc

In ASP.NET MVC 4 I wonder about the behavior, how links are generated for me.
Imagine a simple controller with 3 actions, each taking an integer parameter "requestId", for example:
public class HomeController : Controller
{
public ActionResult Index(int requestId)
{
return View();
}
public ActionResult About(int requestId)
{
return View();
}
public ActionResult Contact(int requestId)
{
return View();
}
}
and this registered route (before the default route):
routes.MapRoute(
name: "Testroute",
url: "home/{action}/{requestId}",
defaults: new { controller = "Home", action = "Index" }
);
I call my index-view using http://localhost:123/home/index/8
On this view, I render links for the other two actions:
#Html.ActionLink("LinkText1", "About")
#Html.ActionLink("LinkText2", "Contact")
Now I expect MVC to render this links including the current route-value for "requestId", like this:
http://localhost:123/home/about/8
http://localhost:123/home/contact/8
But i get these links (without the paramter):
http://localhost:123/home/about
http://localhost:123/home/contact
...but not for the index-action if i would specify one:
#Html.ActionLink("LinkText3", "Index")
What I want to avoid is to explicitly specify the parameters in this manner:
#Html.ActionLink("LinkText1", "Contact", new { requestId = ViewContext.RouteData.Values["requestId"] })
When I move the requestId parameter before the action paramter it works like I expect it, but I don't want to move it:
routes.MapRoute(
name: "Testroute",
url: "home/{requestId}/{action}",
defaults: new { controller = "Home", action = "Index" }
);
Can someone explain me this behavior? How can I get this to work without specifying the parameter explicitly?

InController:
Replace the int to nullable int
For Routing:
set requestId as optional in routing
routes.MapRoute(
name: "Testroute",
url: "home/{action}/{requestId}",
defaults: new { controller = "Home", action = "Index" ,requestId=RouteParameter.Optional }
);

Related

Why we use routing in asp.net mvc

why use custom routing in asp.net MVC
for example
RouteConfig.cs
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
//Enable Routing
routes.MapMvcAttributeRoutes();
//custom route for about page
//routes.MapRoute(
// name:"about",
// url: "Home/About",
// defaults: new { controller = "Home",action= "About", id=UrlParameter.Optional}
// );
//custom route for contactus page
//routes.MapRoute(
// name: "about",
// url: "Home/ContactUs",
// defaults: new { controller = "Home", action = "ContactUs", id = UrlParameter.Optional }
// );
//default route
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
HomeController.cs
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
//[Route("Home/About")]
public ActionResult About()
{
return View();
}
//[Route("Home/ContactUs")]
public ActionResult ContactUs()
{
return View();
}
}
Index.cshtml
IndexPage
About.cshtml
AboutPage
Contactus.cshtml
ContactusPage
when I run the project then write the URL manually then also give output then why use the routing attribute
home/index
home/about
home/contactus
I comment the route attribute and custom route code and above URL give the proper output then why use route attribute
my question is without route attribute easily run the action method then why need to use route attribute above the controller
If you are happy with the default routes, then you don't need to use the route attributes, or put any custom routes in the RouteConfig.
You can add routes to customise how users get to your pages, either through parameters for more dynamic pages, or to make page urls more friendly - for example:
//make about us page url "/about"
routes.MapRoute(
name:"about",
url: "about",
defaults: new { controller = "Home",action= "About"}
);
//make a product page expect an id param in the url
//for example "/catalog/product/pid1"
//"/catalog/product/pid2"
//"/catalog/product/pid3"
//"/catalog/product/pid4" all match this route
routes.MapRoute(
name:"product",
url: "catalog/product/{productId}",
defaults: new { controller = "Catalog",action= "Product"}
);
The same can be achieved in route attributes:
[Route("about")]
public ActionResult AboutUs()
{
return View();
}
[Route("catalog/product/{productId}")]
public ActionResult GetProduct(string productId)
{
//Get product, build view data etc...
return View();
}

MVC ActionLink advice

I'm just starting out with .NET, and am building a test application. I currently have the homepage set using a DefaultController, and an Index() action method. This works as expected, and the homepage is simple www.domain.com.
I have created 2 new pages (Terms and Privacy) under the same DefaultController, using Terms() and Privacy() action methods.
I want to be able to browse to these with the URL as www.domain.com/terms and www.domain.com/privacy.
When i use a <li>#Html.ActionLink("Terms of Service", "Terms", "Default")</li> it works, but it takes me to the URL at www.domain.com/Default/privacy.
Should i be creating seperate controllers for each of these pages, or am I using the #html.ActionLink helper incorrectly? I have previously used <li>Privacy Policy</li> but I understand this isn't best practice?
Also, is there a way to force links as lowercase?
My Controller Code:
public class DefaultController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Terms()
{
return View();
}
public ActionResult Privacy()
{
return View();
}
}
If these were in the HomeController I don't believe you'd have the same problem. However, I think you can get around this by using the RouteConfig file:
routes.MapRoute(
name: "Default",
url: "{Action}/{Id}",
defaults: new { controller = "Default", Action = "Index", Id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Generic",
url: "{controller}/{Action}/{Id}",
defaults: new { Action = "Index", Id = UrlParameter.Optional }
);
I believe that what you want to do is hide the controller name in the url. If that is the case, your question is answered here:
ASP.NET MVC - Removing controller name from URL
You can use Attribute routing to give specific routes to endpoints.
[Route("terms")]
public ActionResult Terms()
{
return View();
}
[Route("privacy")]
public ActionResult Privacy()
{
return View();
}
In your RouteConfig.cs you must enable attribute routing with the following line of code: routes.MapMvcAttributeRoutes();
Now any urls generated with #Url.Action() or #Html.ActionLink should generate URLS as domain.com/privacy and domain.com/terms

MVC Routes with/without actions and with/without id

I have an asp.net MVC site and i would like to go to a controller without an action, but i would also like to be able to give an action on the same or other controllers.
So lets say i have Page.
I would like to be able to access the following urls
MY_URL (nothing else) - This would get another page with id = 1, or name = Home (business logic doesnt matter)
MY_URL/Page/id - This will get a page with a particular Id
MY_URL/Page/Create - Create a new page
MY_URL/Page/Delete - Delete a page
MY_URL/Page/Edit - Edit a page
I thought this would do it, but Create/Delete/Edit dont work (they just go to MY_URL/page with no id)
routes.MapRoute(
name: "PageWithId",
url: "Page/{id}",
defaults: new { controller = "Page", action = "Index" }
);
routes.MapRoute(
name: "default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Page", action = "Index", id = UrlParameter.Optional }
);
Here is my controller
public class PageController : Controller
{
private PageService _service;
public PageController(PageService service)
{
_service = service;
}
public async Task<ActionResult> Index(int? id)
{
... code to get page if id <> null
... code to get home page id id = null
// return view
return View(model);
}
public ActionResult Create()
{
return View();
}
... Delete, Edit methods implemented
}
Any help would be appreciated

Why does #Html.ActionLink not use RouteData

I have the simplest setup:
An empty asp.net MVC application with one controller:
public class HomeController : Controller
{
public ActionResult Edit(int id)
{
return View();
}
public ActionResult Commit(int id)
{
return View();
}
}
My Edit.cshtml has a call to ActionLink() like so:
#Html.ActionLink("Commit Data", "Commit")
If I now access the Edit-Action through "/Home/Edit/2" I would expect that the rendered link directs the user to "/Home/Commit/2".
It does not :( ... The link is created to "Home/Commit", completely disregarding the current RouteData entries.
I am using the default routing configuration (have not added any routes).
One way to fix this would be to add an explicit route for both actions:
routes.MapRoute(
name: null,
url: "Home/Edit/{id}",
defaults: new { controller = "Home", action = "Edit" }
);
routes.MapRoute(
name: null,
url: "Home/Commit/{id}",
defaults: new { controller = "Home", action = "Commit" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
This works - but I really dont want to explicitly define every single route in the app - if I am using the "default" pattern...
The second solution would be to just add the routing-values manually like so:
#Html.ActionLink("Commit Data", "Commit", "Home", new {id = Model.Id})
But this also seems not right - ActionLink SHOULD use the current routing information, should it not?
What am I missing?
Ok, in case someone else is wondering the same thing - or just wants to have a solution that works...
I simply created my own #ActionLink() helper method on my custom ViewPage base class:
protected MvcHtmlString ActionLink(string linkText, string actionName)
{
var routeData = ViewContext.RequestContext.RouteData;
var id = routeData.Values["id"];
if (id != null)
return Html.ActionLink(linkText, actionName, new {id = id});
return Html.ActionLink(linkText, actionName);
}
This is exactly what I wanted. Now I can call
#ActionLink("Commit", "Commit")
and when I'm in the context of something with an id, the link will point to the appropriate route for this Id.

Parameter not being passed to Controller's action in ASP.NET MVC

I have two actions in a controller and yet the parameters are not being passed into one of them.
This one: /RouteStop/List/1
And this one: /RouteStop/Details/100
And my global.asax:
routes.MapRoute(
"List",
"{controller}/{action}/{id}",
new { controller = "RouteStop", action = "List", id = UrlParameter.Optional }
);
routes.MapRoute(
"Details",
"{controller}/{action}/{routeID}",
new { controller = "RouteStop", action = "Details", routeID = UrlParameter.Optional }
);
And here's the actions from my Controller:
public ActionResult List(string id)
{
return View();
}
public ActionResult Details(string routeID)
{
return View();
}
When I access this URL (/RouteStop/Details/100) the parameter gets passed just fine. But when I access the other one (/RouteStop/List/1) the parameter is null. The names match up as they should but I can't figure it out.
Try replacing {controller} with List and Details in respective routes. but for your scenario the default routing that you get when you create an MVC app should work.

Resources