Moh*_*eza 13 c# asp.net-mvc redirect asp.net-mvc-5
我想重定向到其他Controller中的一个动作,但它在这里不起作用我的ProductManagerController中的代码:
[HttpPost]
public ActionResult RedirectToImages(int id)
{
return RedirectToAction("Index","ProductImageManeger", new { id=id });
}
Run Code Online (Sandbox Code Playgroud)
这在我的ProductImageManagerController中:
[HttpGet]
public ViewResult Index(int id)
{
return View("Index",_db.ProductImages.Where(rs=>rs.ProductId == id).ToList());
}
Run Code Online (Sandbox Code Playgroud)
它没有参数很好地重定向到ProductImageManager/Index(没有错误)但是使用上面的代码我得到这个:
参数字典包含"... Controllers.ProductImageManagerController"中方法"System.Web.Mvc.ViewResult Index(Int32)"的非可空类型"System.Int32"的参数"ID"的空条目.可选参数必须是引用类型,可空类型,或者声明为可选参数.参数名称:参数
Bin*_*nke 18
对于同一控制器中的重定向,您无需指定控制器.不确定你是否需要让参数为nullable来进行这种重定向,或者如果我们将它作为可空的,因为我们需要另外一次,但这是来自一个工作项目:
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 }
);
}
Run Code Online (Sandbox Code Playgroud)
编辑
调用不同的控制器,您可能需要使用RouteValueDictionary:
[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 });
}
Run Code Online (Sandbox Code Playgroud)
如果为其配置了RouteConfig,则您提供的示例应该有效,因此您应该检查它以便正确设置它.有关更多信息,请查看此stackoverflow问题和答案.
编辑2:
根据@Mohammadreza的评论,错误发生在RouteConfig中.要让应用程序处理带有id的URL,您需要确保为其配置了Route.您可以在位于App_Start文件夹中的RouteConfig.cs中执行此操作.
return RedirectToAction("Index", new RouteValueDictionary(
new { controller = "ProductImageManager", action = "Index", id = id } )
);
Run Code Online (Sandbox Code Playgroud)
LIN*_*dka -2
return RedirectToAction("ProductImageManager","Index", new { id=id });
Run Code Online (Sandbox Code Playgroud)
这是无效的参数顺序,应该首先采取行动
并
确保您的路由表正确
归档时间: |
|
查看次数: |
104494 次 |
最近记录: |