问题
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
回答1:
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() });
来源:https://stackoverflow.com/questions/29022582/how-to-redirect-to-route-using-custom-attribute-routing-in-mvc5