如何使用自定义属性,MVC5路由重定向路由 [英] How to redirect to route using custom attribute routing in MVC5
问题描述
我不知道,如果有什么我试图做的是有效的,因为我是一个新手相对的C#/ ASP.NET / MVC堆栈。
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.
我有这样的控制器操作的 ModelController.cs
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);
}
和在另一个名为控制器的 VehicleMakeController.cs ,我有以下几点:
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);
}
我想什么做的,就是在我返回时,一个数据库更新成功,重定向到我定义(自定义路线这一部分:返回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?
在此先感谢
推荐答案
指定的路线并不自动意味着该路由值供给。你仍然需要为了使路由匹配请求手动提供给他们。
Specifying a route 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.
在这种情况下,你的路线需要一个 vehicleMake
参数。我不知道究竟你会如何转换您的 vehicleMake
键入可与您的路线使用的字符串,所以我只是展示的ToString
在这个例子中。
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 });
这篇关于如何使用自定义属性,MVC5路由重定向路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!