【问题标题】:how to route forms in ASP.NET MVC如何在 ASP.NET MVC 中路由表单
【发布时间】:2020-07-07 21:57:28
【问题描述】:

当我使用搜索参数搜索产品时,我想重定向 url /products/search/ 或 /products/id/search。

  routes.MapRoute(
               name: "products",
               url: "products/{id}/{search}/{page}",
               defaults: new { controller = "products", action = "Index", id = UrlParameter.Optional, page = UrlParameter.Optional }
            );

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { action = "Index",id = UrlParameter.Optional }
            );

当我在显示 /products?search=parametername 的搜索框 url 中搜索产品时。但是当点击显示 /products/search 的菜单项 url 时。

【问题讨论】:

    标签: asp.net asp.net-mvc url-routing asp.net-mvc-routing


    【解决方案1】:

    将 [HttpGet("{id:int}")] 添加到控制器中方法的顶部。
    像这样:

        [HttpGet("{id:int}")]
        public virtual async Task<ApiResult<List<PostShortSelectDto>>> GetSimilar(CancellationToken cancellationToken, int id)
        {
            return await _postRepository.GetSimilar(cancellationToken, id);
        }
    

    现在路由器是这样的:
    /Controller/GetSimilar/1

    如果使用 .net mvc ,请使用以下代码:

        [HttpGet]
        [Route("GetSimilar/{id}")]
        public virtual async Task<ApiResult<List<PostShortSelectDto>>> GetSimilar(CancellationToken cancellationToken, int id)
        {
            return await _postRepository.GetSimilar(cancellationToken, id);
        }
    

    【讨论】:

    • 显示“HttpGetAttribute 不包含采用 1 个参数的构造函数”错误
    • 什么都没有改变。显示 /products?search=parametername 的网址
    • @userhk 我写了一个例子,如果你想传递 id 作为 int,如果你想传递字符串参数作为搜索,你应该改变 MapRoute
    猜你喜欢
    • 1970-01-01
    • 2014-02-09
    • 2010-09-21
    • 1970-01-01
    • 1970-01-01
    • 2020-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多