简体   繁体   English

如何在MVC5中使用自定义属性路由重定向到路由

[英]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. 我不确定我尝试做的是否有效,因为我是C#/ ASP.NET / MVC堆栈的相对新手。

I have a controller action like this in ModelController.cs 我在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: 在另一个名为VehicleMakeController.cs的控制器中,我有以下内容:

[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"); ) 我想做的是,当数据库更新成功时我正在返回的地方,重定向到我定义的自定义路由(这部分: 返回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. 在这种情况下,您的路线需要vehicleMake参数。 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. 我不确定你如何将你的vehicleMake类型转换为可以与你的路线一起使用的字符串,所以我只是在这个例子中显示ToString

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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