简体   繁体   中英

How to redirect to route using custom attribute routing in MVC5

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

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() });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM