加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – ASP.NET MVC路由中未传递的参数值

发布时间:2020-12-16 06:36:56 所属栏目:asp.Net 来源:网络整理
导读:我正在学习如何在ASP.NET MVC中创建自定义路由并且遇到了障碍.在我的Global.asax.cs文件中,我添加了以下内容: public static void RegisterRoutes(RouteCollection routes){ routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Default"
我正在学习如何在ASP.NET MVC中创建自定义路由并且遇到了障碍.在我的Global.asax.cs文件中,我添加了以下内容:

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

    routes.MapRoute(
        "Default",// Route name
        "{controller}/{action}/{id}",// URL with parameters
        new { controller = "Home",action = "Index",id = UrlParameter.Optional } // Parameter defaults
    );

    // My Custom Route.
    routes.MapRoute(
        "User_Filter","home/filter/{name}",new { controller = "Home",action = "Filter",name = String.Empty }
    );
}

我的想法是能够导航到http:// localhost:123 / home / filter / mynameparam.这是我的控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult Filter(string name)
    {
        return this.Content(String.Format("You found me {0}",name));
    }
}

当我导航到http:// localhost:123 / home / filter / mynameparam时,将调用控制器方法Filter,但参数名称始终为null.

有人可以给出一个指针,指出我构建自定义路由的正确方法,以便它将url中的name部分传递给Filter()的name参数.

解决方法

默认路由应该是最后一个.
试试这种方式:

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

    // My Custom Route.
    routes.MapRoute(
        "User_Filter",name = String.Empty }
    );

    routes.MapRoute(
        "Default",id = UrlParameter.Optional } // Parameter defaults
    );
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读