Dynamic MVC Routing : Action name - asp.net-mvc

I have a Controller named About and an Action named Index. I want the URL to be like this (action name will be dynamically):
www.example.com/about/aaa
www.example.com/about/bbb
www.example.com/about/ccc
Routing
routes.MapRoute(
name: "About",
url: "{controller}/{name}",
defaults: new { controller = "About", action = "Index"}
Controller
public class AboutController : Controller
{
// GET: /About/
public ActionResult Index(string name)
{
return View();
}
}
View
#{
ViewBag.Title = "Index";
}
<h2>Index About</h2>

This should work.
routes.MapRoute(
name: "About",
url: "About/{name}",
defaults: new
{
controller = "About",
action = "Index"
});
Make sure your default route exists and comes after About route

routes.MapRoute(
name: "About",
url: "about/{name}/{id}",
defaults: new { controller = "About", action = "Index", id=UrlParameter.Optional}

You can pass an ActionResult name as a parameter:
public ActionResult Index(string name)
{
return View(name);
}
public ActionResult First()
{
return View();
}
public ActionResult Second()
{
return View();
}
In the View:
#Html.ActionLink("Get Action named Firts" "Index", "Home", new {name = "First"}, null)

Related

i want to implement route like webapi in mvc

I am invoking the url "localhost/Student/1" to return the student with id=1. My route config:
routes.MapRoute(
name: "StudentID",
url: "Student/{id}",
defaults: new { controller = "Student", action = "Get}
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Student", action = "Index", id = UrlParameter.Optional }
);
public class StudentController : Controller
{
// GET: Student
[Authorize]
public ActionResult Index()
{
SchoolDbEntities db = new SchoolDbEntities();
return View(db.Students);
}
[Route("Student/{id}")]
[ActionName("Get")]
public ActionResult Get(int id)
{
SchoolDbEntities db = new SchoolDbEntities();
var student = db.Students.Where(s => s.Id == id);
return View(student);
}
}
I configured both route table and use route attributes.
However when i run the application it throws an error:
The resource cannot be found.
how do i implement the same as using webapi.
If you want to use attribute routes in MVC you must register them by calling routes.MapMvcAttributeRoutes() in your RouteConfig class.
Note that the registration order matters. By putting the call to route.MapMvcAttributeRoutes() before your routes.MapRoute() call MVC will look at the attribute routes before the traditional routes. The first matching route wins.
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Student", action = "Index", id = UrlParameter.Optional }
);
In your controller setup your attribute routing like this:
[RoutePrefix("Student")]
public class StudentController : Controller
{
// GET: Student
[Authorize]
public ActionResult Index()
{
SchoolDbEntities db = new SchoolDbEntities();
return View(db.Students);
}
[Route("{id}")]
public ActionResult Get(int id)
{
SchoolDbEntities db = new SchoolDbEntities();
var student = db.Students.Where(s => s.Id == id);
return View(student);
}
}
This will match the URL "Student/1".

Route issue with subfolder in Controllers

we have decided to use subfolders in our Controllers folder. All our controllers are working like they should, but for one reason or another it doesn't get in the Controller method when we add an {id}
Route:
routes.MapRoute(
name: "Maintenance",
url: "Maintenance/{controller}/{action}/{id}",
defaults: new { controller = "TargetAudience", action = "Index", id = UrlParameter.Optional },
namespaces: new string[] { "IstPhenix.Controllers.Maintenance" }
);
This matches URLs like
/Maintenance/Category/Index
but whenever we add the {id} like /Maintenance/Category/Edit/123456789 the Controller method cannot be found
CategoryController.cs:
[ClaimsAuthorize(PhenixPermissions = "ConsultCategory")]
public ActionResult Edit(int id)
{
ViewBag.CategoryId = id;
return View("~/Views/Maintenance/Category/Edit.cshtml", id);
}
[ClaimsAuthorize(PhenixPermissions = "ConsultCategory")]
public ActionResult Index()
{
return View("~/Views/Maintenance/Category/Index.cshtml");
}
Usefull to mention is that we also have a default route at the end of our RouteConfig:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new string[] { "IstPhenix.Controllers.Enduser", "IstPhenix.Controllers.Maintenance", "IstPhenix.Controllers.Security" }
);
And then following URLs work when we omit the subfolder:
/Category/Index
/Category/Edit/123456789
Any idea why the URL does not match the route when i have a subfolder and an id?
What am i missing?
tnx!
What if you added a Route attribute:
[Route("Maintenance/Category/Edit/{id}")]
[ClaimsAuthorize(PhenixPermissions = "ConsultCategory")]
public ActionResult Edit(int id)
{
ViewBag.CategoryId = id;
return View("~/Views/Maintenance/Category/Edit.cshtml", id);
}
That would explicitly give the route to the action.

ASP.NET MVC Overriding Index action with optional parameter

I want to accept /User/ and /User/213123
Where 213123 is a parameter (user_id)
Here is my RouteConfig.cs:
routes.MapRoute(
name: "user",
url: "{controller}/{action}/{username}",
defaults: new { controller = "User", action = "Index", username = UrlParameter.Optional }
);
And my UserController.cs:
public ActionResult Index()
{
ViewData["Message"] = "user index";
return View();
}
[Route("user/{username}")]
public ActionResult Index(string username)
{
ViewData["Message"] = "!" + username + "!";
return View();
}
This works in .net-core 1.0 but not in mvc5. What am I missing?
Thank you
EDIT:
Having just this in my UserController.cs also doesn't work (returns 404):
public ActionResult Index(string username)
{
if (!String.IsNullOrEmpty(username))
{
ViewData["Message"] = "Hello " + username;
}
else
{
ViewData["Message"] = "user index";
}
return View();
}
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /user/asd
EDIT2:
Updated RouteConfig.cs:
routes.MapRoute(
"userParam", "user/{username}",
new { controller = "user", action = "IndexByUsername" },
new { username = #"\w+" }
);
routes.MapRoute(
name: "user",
url: "user",
defaults: new { controller = "User", action = "Index"}
);
/User/ now calls IndexByUsername with Index as the username
/User/asd still returns 404
EDIT4: Current code:
RouteConfig.cs:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/",
defaults: new { controller = "Home", action = "Index" }
);
routes.MapRoute("userParam", "user/{username}", new { controller = "user", action = "Index"});
routes.MapRoute("user", "{controller}/{action}/{username}", new { controller = "User", action = "Index", username = UrlParameter.Optional });
UserController.cs:
public class UserController : Controller
{
public ActionResult Index(string username)
{
if (!String.IsNullOrEmpty(username))
{
ViewData["Message"] = "Hello " + username;
}
else
{
ViewData["Message"] = "user index";
}
return View();
}
}
You need only one action method with the signature
public ActionResult Index(string username)
and in that method you can check if the value of username is null or not.
Then you route definitiosn needs to be (note the user route needs to be placed before the default route)
routes.MapRoute(
name: "user",
url: "user/{username}",
defaults: new { controller = "User", action = "Index", username = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

How to display only name in url instead of id in mvc.net using routing

I am getting url like http://localhost:49671/TestRoutes/Display?f=hi&i=2
I want it like http://localhost:49671/TestRoutes/Display/hi
I call it from Index method.
[HttpPost]
public ActionResult Index(int? e )
{
// return View("Display", new { f = "hi", i = 2 });
return RedirectToAction("Display", new { f = "hi", i = 2 });
}
Index view
#model Try.Models.TestRoutes
#using (Html.BeginForm())
{
Model.e = 5 ;
<input type="submit" value="Create" class="btn btn-default" />
}
Display Action method
// [Route("TestRoutes/{s}")]
public ActionResult Display(string s, int i)
{
return View();
}
Route config file
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Professional", // Route name
"{controller}/{action}/{id}/{name}", // URL with parameters
new { controller = "TestRoutes", action = "Display", s = UrlParameter.Optional, i = UrlParameter.Optional
});
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional
});
You need to change your route definition to
routes.MapRoute(
name: "Professional",
url: "TestRoutes/Display/{s}/{i}",
default: new { controller = "TestRoutes", action = "Display", i = UrlParameter.Optional }
);
so that the names of the placeholders match the names of the parameters in your method. Note also that only the last parameter can be marked as UrlParameter.Optional (otherwise the RoutingEngine cannot match up the segments and the values will be added as query string parameters, not route values)
Then you need to change the controller method to match the route/method parameters
[HttpPost]
public ActionResult Index(int? e )
{
return RedirectToAction("Display", new { s = "hi", i = 2 }); // s not f
}
change your route as
routes.MapRoute(
"Professional", // Route name
"{controller}/{action}/{name}", // URL with parameters
new
{
controller = "TestRoutes",
action = "Display"
} // Parameter defaults
);
and your action as
public ActionResult Display(string name)
{
//action goes here
}
Remove the maproute code:
routes.MapRoute(
"Professional", // Route name
"{controller}/{action}/{id}/{name}", // URL with parameters
new { controller = "TestRoutes", action = "Display", s = UrlParameter.Optional, i = UrlParameter.Optional
});
Use attribute routing code:
[Route("TestRoutes/{s}/{i?}")]
public ActionResult Display(string s, int? i)
{
return View();
}
You can also try using Attribute Routing. You can control your routes easier with attribute routing.
Firstly change your RouteConfig.cs like that:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
//routes.MapRoute(
// name: "Default",
// url: "{controller}/{action}/{id}",
// defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
//);
}
}
After that change your controller files like that:
namespace YourProjectName.Controllers
{
[RoutePrefix("Home")]
[Route("{action}/{id=0}")]
public class HomeController : Controller
{
[Route("Index")]
public ActionResult Index()
{
return View();
}
[Route("ChangeAddress/{addressID}")]
public ActionResult ChangeAddress(int addressID)
{
//your codes to change address
}
}
You can also learn more about Attribute Routing in this post:
https://blogs.msdn.microsoft.com/webdev/2013/10/17/attribute-routing-in-asp-net-mvc-5/
Another way to solve this problem is to put the proper route before the default route, as follows:
routes.MapRoute(name: "MyRouteName", url: "Id", defaults: new { controller= "Home", action = "Index",id= Id });
Default route:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{Id}",
defaults: new { controller = "Home", action = "Index",id= Id }
);

Url Routing Help Asp.net Mvc

I have three url types. These:
first: http://localhost/
second: http://localhost/X/
third: http://localhost/X/Y/
Examples Url:
http://localhost/test/
http://localhost/test/details/
first:
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new
{
controller = "Home",
action = "Index",
id = UrlParameter.Optional
}
);
public class HomeController : Controller
{
// GET: /Home/
public ActionResult Index()
{
return View();
}
}
second:
routes.MapRoute(
"Module",
"{module_name}/{controller}/{action}",
new
{
controller = "Module",
action = "Index",
module_name = UrlParameter.Optional
}
);
public class ModuleController : Controller
{
//
// GET: /Module/
public ActionResult Index(string modul_name)
{
return View();
}
}
third:
routes.MapRoute(
"ModuleDetails",
"{module_name}/{details_param}/{controller}/{action}",
new
{
controller = "ModuleDetails",
action = "Index",
module_name = UrlParameter.Optional,
details_param = UrlParameter.Optional
}
);
public class ModuleDetailsController : Controller
{
//
// GET: /ModuleDetails/
public ActionResult Index(string modul_name, string details_param)
{
return View();
}
}
in this instance;
http://localhost/X/
response: "Home", "Index"
but;
http://localhost/X/
response: Application in the server error. Resource Not Found.
http://localhost/X/Y/
response: Application in the server error. Resource Not Found.
How can I do?
Thanks, best regards..
http://localhost/X/
response: Application in the server error. Resource Not Found.
This happens because each of your routes specifies at least 2 mandatory parameters.
Try to add this one:
routes.MapRoute(
"Default",
"{controller}/{action}",
new
{
controller = "Home",
action = "Index"
}
);
that's right friends..
routes.MapRoute(
"Default", // Route name
"", // URL with parameters
new { controller = "Home", action = "Index" } // Parameter defaults
);
routes.MapRoute(
"Module",
"{modul_name}",
new { controller = "Modul", action = "Index", modul_name = UrlParameter.Optional }
);
routes.MapRoute(
"Page",
"{modul_name}/{page_name}",
new { controller = "Page", action = "Index", modul_name = UrlParameter.Optional, page_name = UrlParameter.Optional }
);

Resources