首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >重定向到按参数mvc执行的操作

重定向到按参数mvc执行的操作
EN

Stack Overflow用户
提问于 2013-11-12 21:04:29
回答 4查看 128.5K关注 0票数 15

我想要重定向到其他控制器中的操作,但它不起作用。下面是我在ProductManagerController中的代码:

代码语言:javascript
复制
[HttpPost]
public ActionResult RedirectToImages(int id)
{
    return RedirectToAction("Index","ProductImageManeger", new   { id=id   });
}

在我的ProductImageManagerController中:

代码语言:javascript
复制
[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

EN

回答 4

Stack Overflow用户

发布于 2013-11-12 21:33:29

这个错误是非描述性的,但这里的关键是'ID'是大写的。这表示路由设置不正确。要让应用程序处理具有id的URL,您需要确保至少为其配置了一条路由。您可以在位于App_Start文件夹中的RouteConfig.cs中执行此操作。最常见的是将id作为可选参数添加到默认路由。

代码语言:javascript
复制
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 }
    );
}

现在,您应该能够按照设置的方式重定向到控制器。

代码语言:javascript
复制
[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的更多信息

代码语言:javascript
复制
return RedirectToAction("Index", new RouteValueDictionary( 
    new { controller = "ProductImageManager", action = "Index", id = id } ) 
);

如果你得到一个非常类似的错误,但是在小写的' id '中,这通常是因为路由需要一个没有提供的id参数(调用一个没有id/ProductImageManager/Index的路由)。有关详细信息,请参阅this so question

票数 21
EN

Stack Overflow用户

发布于 2018-06-08 04:00:49

这应该行得通!

代码语言:javascript
复制
[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());
}

请注意,如果返回的视图与操作实现的视图相同,则不必传递视图的名称。

您的视图应该继承模型,如下所示:

代码语言:javascript
复制
@model <Your class name>

然后,您可以在视图中访问模型,如下所示:

代码语言:javascript
复制
@Model.<property_name>
票数 -1
EN

Stack Overflow用户

发布于 2013-11-12 21:06:13

代码语言:javascript
复制
return RedirectToAction("ProductImageManager","Index", new   { id=id   });

这是一个无效的参数顺序,应该首先是一个动作

确保您的路由表是正确的

票数 -2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19929990

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档