Reputation: 8302
So I have the following route in my RouteConfig.cs
routes.MapRoute(
name: "Student",
url: "student",
defaults: new { controller = "Home", action = "Student", id = UrlParameter.Optional }
);
Based on this route, I have the following method in my Home
controller:
public ActionResult Student()
{
return View();
}
This simple route when invoked http://localhost:54326/student
will take me to the Student view. All good till now.
How can I achieve this route: http://localhost:54326/student/01-28-2021
when I invoke the above route automatically?
Basically, I want to append a string at the end of the original route when it is invoked.
Is there anything I can specify in RouteConfig
through which I can achieve this?
Upvotes: 1
Views: 339
Reputation: 8915
The following route Student
will allow to append a string at the end of http://localhost:54326/student
when it is invoked.
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// It is important that you add this route before the `Default` one.
// Routes are processed in the order they are listed,
// and we need the new route to take precedence over the default.
routes.MapRoute(
name: "Student",
url: "Student/{date}",
defaults: new { controller = "Home", action = "Student", date = UrlParameter.Optional}
);
The Student
action declaration:
public ActionResult Student(string date)
{
//string dateFormat = "MM-dd-yyyy";
string dateFormat = "dd-MM-yyyy";
if (string.IsNullOrEmpty(date))
{
return RedirectToAction("Student", new { date = DateTime.Now.ToString(dateFormat) });
}
else if (!DateTime.TryParseExact(date, dateFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime dt))
{
return RedirectToAction("ReportErrorFormat");
}
return View((object)date);
}
Upvotes: 1