简体   繁体   中英

how to route forms in ASP.NET MVC

When I search for a product with search parameter, I want to redirect url /products/search/ or /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 }
            );

When I search for a product in searchbox url showing /products?search=parametername. But when clicking in menu item url showing /products/search.

add [HttpGet("{id:int}")] to top of your method in controller.
like this:

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

Now router is like this:
/Controller/GetSimilar/1

If use .net mvc , use this code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM