我想重定向到其他Controller中的操作但它不起作用
这是我在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 / Index(没有错误) 但是上面的代码我得到了这个:
参数字典包含空条目
方法的非可空类型'System.Int32'的参数'ID'
'System.Web.Mvc.ViewResult Index(Int32)'中
'... Controllers.ProductImageManagerController'。
可选参数必须是引用类型,可空类型或be
声明为可选参数。参数名称:参数
对于同一控制器中的重定向,您无需指定控制器。不确定你是否需要让参数为nullable来进行这种重定向,或者如果我们将它作为可空的,因为我们需要另外一次,但这是来自一个工作项目:
[HttpGet]
public ActionResult EditRole(int? selectedRoleId)
{
AddEditRoleViewModel role = _userService.GetAllRoles(selectedRoleId);
return View(role);
}
[HttpPost]
public ActionResult EditRoleSave(AddEditRoleViewModel role)
{
_userService.SaveRole(role);
return RedirectToAction("EditRole", new { selectedRoleId = role.Id });
}
编辑
调用不同的控制器,您可能需要使用a RouteValueDictionary:
return RedirectToAction("Index", new RouteValueDictionary(
new { controller = "ProductImageManager", action = "Index", id= id } )
);
您提供的示例应该适用于您的 RouteConfig 是为它配置的,所以你应该检查它,以便你正确设置它。检查 这个stackoverflow问题 和答案了解更多信息。
编辑2:
根据@Mohammadreza的评论,错误发生在 RouteConfig。
要让应用程序处理带有id的URL,您需要确保为其配置了Route。你这样做 RouteConfig.cs 位于 App_Start 夹。
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
//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", "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>
尝试这个,
return RedirectToAction("ActionEventName", "Controller", new { ID = model.ID, SiteID = model.SiteID });
在这里我提到你也传递了多个值或模型。
这就是我在这里提到的原因。
return RedirectToAction("ProductImageManager","Index", new { id=id });
这是一个无效的参数顺序,应该是一个动作第一个
和
确保您的路由表正确无误