I can't wrap my mind around the routing mechanism in asp.net core MVC 2.
Here's what I have:
I already built a functioning page to add 'Materials' to a 'Application'.
The URL to call this page is:
http://localhost:33333/AddMaterial/Index/57
which uses the default route:
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}"
);
Whereby 57 is the application id, so that I know what 'Application' gets the new 'Material'. The Index Method in the controller looks like this, and works like expected:
[HttpGet] public IActionResult Index(string id)
{
var model = GetModel(context, int.Parse(id));
return View("Index", model);
}
So far so good... Now here's my problem:
I want to use the same controller and view to also edit 'Materials'. But for that i'd need two parameters in Index(). I'd need:
string applicationId
string materialId
as parameters.
So I added a new route:
routes.MapRoute(
name: "whatImTryingToAchieve",
template: "{controller}/{action}/{applicationId?}/{materialId?}"
);
And of course I updated the controller:
public IActionResult Index(string applicationiId, string materialId)
{
// Do stuff with materialId etc.
// ...
return View("Index", model);
}
I know that the routing system has a specific order. So I tried defining my new route before the default route. That didn't work. I then tried to put it after the default route, which didn't work either.
I read through a lot of information about the routing system, but I didn't seem to find the answer to my simple question:
How can I add another, specific route?
Help would be much appreciated :)
EDIT: Attribute based routing as suggested by Igors Šutovs
Controller:
[Authorize(Roles = "Admins")]
[Route("AddMaterial")]
public class AddMaterialController : Controller
{
//....
[Route("AddMaterial/{applicationId}/{otherid}")] // Nope. Nothing.
[HttpGet] public IActionResult Index(string applicationId, string otherid)
{
return View();
}
[Route("AddMaterial/Index/{applicationId}")] // Didn't work.
[Route("AddMaterial/{applicationId}")] // Didn't work either...
[HttpGet] public IActionResult Index(string applicationId)
{
return View();
}
}
So much for Attribute base routing.
applicationiIdin theIndexaction? I don't expect that's the entirety of your problem, but it's not a good start.