我想要重定向到其他控制器中的操作,但它不起作用。下面是我在ProductManagerController中的代码:
[HttpPost]
public ActionResult RedirectToImages(int id)
{
return RedirectToAction("Index","ProductImageManeger", new { id=id });
}
在我的ProductImageManagerController中:
[HttpGet]
public ViewResult Index(int id)
{
return View("Index",_db.ProductImages.Where(rs=>rs.ProductId == id).ToList());
}
不带参数重定向到ProductImageManager/非常好(没有错误),但使用上面的代码我得到了:
参数字典包含'...Controllers.ProductImageManagerController'.中“”System.Web.Mvc.ViewResult索引(Int32)“”方法的不可为空类型“”System.Int32“”的参数“”ID“”的null条目“”可选参数必须是引用类型、可以为must的类型或声明为可选参数。参数名称: parameters
发布于 2013-11-12 21:33:29
这个错误是非描述性的,但这里的关键是'ID'是大写的。这表示路由设置不正确。要让应用程序处理具有id的URL,您需要确保至少为其配置了一条路由。您可以在位于App_Start文件夹中的RouteConfig.cs中执行此操作。最常见的是将id作为可选参数添加到默认路由。
public static void RegisterRoutes(RouteCollection routes)
{
//adding the {id} and setting is as optional so that you do not need to use it for every action
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
现在,您应该能够按照设置的方式重定向到控制器。
[HttpPost]
public ActionResult RedirectToImages(int id)
{
return RedirectToAction("Index","ProductImageManager", new { id });
//if the action is in the same controller, you can omit the controller:
//RedirectToAction("Index", new { id });
}
在以前的一两次情况下,我通过正常的重定向遇到了一些问题,不得不通过传递一个RouteValueDictionary来解决。有关RedirectToAction with parameter的更多信息
return RedirectToAction("Index", new RouteValueDictionary(
new { controller = "ProductImageManager", action = "Index", id = id } )
);
如果你得到一个非常类似的错误,但是在小写的' id '中,这通常是因为路由需要一个没有提供的id参数(调用一个没有id/ProductImageManager/Index
的路由)。有关详细信息,请参阅this so question。
发布于 2018-06-08 04:00:49
这应该行得通!
[HttpPost]
public ActionResult RedirectToImages(int id)
{
return RedirectToAction("Index", "ProductImageManeger", new { id = id });
}
[HttpGet]
public ViewResult Index(int id)
{
return View(_db.ProductImages.Where(rs => rs.ProductId == id).ToList());
}
请注意,如果返回的视图与操作实现的视图相同,则不必传递视图的名称。
您的视图应该继承模型,如下所示:
@model <Your class name>
然后,您可以在视图中访问模型,如下所示:
@Model.<property_name>
发布于 2013-11-12 21:06:13
return RedirectToAction("ProductImageManager","Index", new { id=id });
这是一个无效的参数顺序,应该首先是一个动作
和
确保您的路由表是正确的
https://stackoverflow.com/questions/19929990
复制相似问题