How to redirect a route using custom attribute routing in MVC5

I'm not sure what I'm trying to do is valid, as I'm a relative newbie to the C # / ASP.NET / MVC stack.

I have a controller action similar to 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 named 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 where I return on a successful db update, redirected to the custom route that I defined (this part: return RedirectToRoute ("NiceUrlForVehicleMakeLookup");)

The views I use are just standard views, can this be achieved or do I need to start exploring Particles or areas?

Thank you in advance

+6
source share
1 answer

Specifying a route name does not automatically mean that route values ​​are specified. You still need to provide them manually so that the route matches the request.

In this case, the vehicleMake argument is required for your route. I don’t know exactly how you would convert your vehicleMake type to a string that can be used with your route, so I just show ToString in this example.

 return RedirectToRoute("NiceUrlForVehicleMakeLookup", new { vehicleMake = vehicleMake.ToString() }); 
+7
source

Source: https://habr.com/ru/post/983726/


All Articles