Can I have an MVC 4 controller that uses number as name?
Sorry if this is a general noob question, but I am trying to create "year" specific controllers to display content.
When I try to create "2015Controller" it adds an underscore in front of the number and then the name of the view. (Not the friendly URL I was looking for.)
I may be a total dope and I skipped this boat, but I would like to split the content on the displays based on the year as I have years of content that I would like to access via simple URLs.
source to share
This sounds like an XY problem .
I can say with a high degree of certainty that you don't have to create a new controller every year. This will give you a huge maintenance load and bloated code (you have to create a new controller and a new controller class every year).
You need to create a small set of controllers (maybe even one), add the ability to skip a year through the URL, and design them to dynamically load and serve content based on a specified year.
Here you can do the "pass a year through the URL" part.
Add this as the first route in RouteConfig.cs:
routes.MapRoute(
name: "Year",
url: "{year}/{action}/{id}",
defaults: new {controller = "Home", action = "Index", id = UrlParameter.Optional},
constraints: new{ year = @"\d{4}" });
This tells the routing module that anytime a URL comes in that starts with 4 digits, it should send that request to the controller Home
(you can change it if you like) and pass those 4 digits as the routing value called year
.
Then in HomeController
you can just add year
as a parameter to your actions:
public ActionResult Index(string year)
{
// use year to fetch and prepare content
return View();
}
public ActionResult Schedule(string year)
{
// use year to fetch and prepare content
return View();
}
So, if a visitor navigates to http://mydomain/2015
or http://mydomain/2015/Index
, this request will be sent to an action Index
with a year
value 2015
. If the visitor navigates to http://mydomain/2016/Schedule
, this request will be sent to an action Schedule
with a year
value 2016
.
Thus, you must be tuned in. If you want to differentiate between views based on year, you can add multiple views and simply pass the required values ββto the helper View()
to show the desired view.
source to share
thanks for the help. I ended up going with "scopes" because it made a little more sense for me. There is a limited amount of content every year, and this allows me to see the structure of things that I'm comfortable with.
The work for me will have to progress in the mapping process. I didn't quite get it, and I felt like I got a little frustrated when I click on time in development.
This site is amazing with all the information I got from it, thank you very much!
source to share