I'm not sure if what I'm attempting to do is valid as I'm a relative newbie to the C# / ASP.NET / MVC stack.
I have a controller action like this in ModelController.cs
//Get
[Route("{vehiclemake}/models", Name = "NiceUrlForVehicleMakeLookup")]
public async Task<ActionResult> Index(string vehicleMake)
{
// Code removed for readaility
models = await db.VehicleModels.Where(make => make.VehicleMake.Make == vehicleMake).ToListAsync();
return View(models);
}
and in another controller called VehicleMakeController.cs, I have the following:
[HttpPost]
[Route("VehicleMake/AddNiceName/{makeId}")]
public ActionResult AddNiceName(VehicleMake vehicleMake, int? makeId)
{
if (ModelState.IsValid)
{
var vehicle = db.VehicleMakes.Find(makeId);
vehicle.MakeNiceName = vehicleMake.MakeNiceName;
db.SaveChanges();
return RedirectToRoute("NiceUrlForVehicleMakeLookup");
}
VehicleMake make = vehicleMake;
return View(make);
}
What I would like to do, is in where I'm returning when a db update is successful, redirect to the custom route I defined ( this part: return RedirectToRoute("NiceUrlForVehicleMakeLookup"); )
The views I'm using are just standard views, can this be accomplished or do I need to start looking into Partials or Areas?
Thanks in advance
Enabling attribute based routing With MVC 5 and attribute based routing, you gain finer control of your routes at both the controller and action level. Enabling attribute routing in your project is simple, just add a call to routes. MapMvcAttributeRoutes(); in your RegisterRoutes function.
To enable Attribute Routing, we need to call the MapMvcAttributeRoutes method of the route collection class during configuration. We can also add a customized route within the same method. In this way we can combine Attribute Routing and convention-based routing. A route attribute is defined on top of an action method.
As per our opinion, Attribute Routing provides us more flexibilities as compared to Convention Based Routing. In Attribute Routing, we can manage route as controller level, action level and also area level. Also, it can override the child route, if required.
In short, Convention Routing approaches Routing from the general case; you generally add some routes that will match all or most of your URLs, then add more specific routes for more specialized cases. The other way to approach this problem is via Attribute Routing.
Specifying a route name doesn't automatically mean that the route values are supplied. You still need to supply them manually in order to make the route match the request.
In this case, your route requires a vehicleMake
argument. I am not sure exactly how you would convert your vehicleMake
type to a string that can be used with your route, so I am just showing ToString
in this example.
return RedirectToRoute("NiceUrlForVehicleMakeLookup", new { vehicleMake = vehicleMake.ToString() });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With