【问题标题】:RedirectToAction with parameters in RouteRedirectToAction 与 Route 中的参数
【发布时间】:2015-02-05 13:55:43
【问题描述】:

如果我在路由或调用 Id 的参数上没有参数,则基本上重定向到某些操作时会遇到一些问题,但当我向路由添加一些不同的参数时,RedirectToAction 不起作用,它会引发错误:没有路由路由表中的值与提供的值匹配。

[Route("First")]
public ActionResult First()
{
    //THIS DOESN'T WORK
    //return RedirectToAction("Second", new { area = "plans"});

    //THIS WORKS
    return RedirectToAction("Third", new { id = "12" });
}

[Route("Second/{area}")]
public ActionResult Second(string area)
{
    return new ContentResult() { Content = "Second : " + area};
}


[Route("Third/{id}")]
public ActionResult Third(string id)
{
    return new ContentResult() { Content = "Third " + id };
}

所以当我输入 /First 时,它会正确重定向到 Third 但到 Second 它会抛出错误。

我在 RouteConfig 中没有任何额外的东西:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.MapMvcAttributeRoutes();
}

【问题讨论】:

    标签: c# asp.net-mvc asp.net-mvc-routing


    【解决方案1】:

    您可能将area 参数与area 路由参数冲突。 Areas is a resource from Asp.Net MVC 定义如下:

    区域是控制器、模型和视图等的逻辑分组 MVC 应用程序中模块的相关文件夹。按照惯例,顶部 区域文件夹可以包含多个区域。使用区域,我们可以写 更易于维护的应用程序代码 到模块。

    您可以尝试重命名此参数并使用它,例如,尝试将 area 重命名为 areaName

    [Route("First")]
    public ActionResult First()
    {
        return RedirectToAction("Second", new { areaName= "plans"});
    }
    
    [Route("Second/{areaName}")]
    public ActionResult Second(string areaName)
    {
        return new ContentResult() { Content = "Second : " + areaName};
    }
    

    【讨论】:

    • 你是对的!它适用于哪个区域名称,但是有没有办法将区域作为参数发送?假设我们有 Route("{area}/Second") 以及如何重定向到不同的区域?
    • 同意。 ASP.NET MVC 在路由站点中的任何区域时使用{area}。因此,建议将该参数重命名为其他名称以避免混淆。
    猜你喜欢
    • 2012-07-09
    • 2010-11-18
    • 1970-01-01
    • 2021-10-07
    • 2011-09-25
    • 1970-01-01
    • 2021-01-07
    • 2020-03-12
    • 1970-01-01
    相关资源
    最近更新 更多