Search form does not execute controller method

Asked

Viewed 59 times

2

I have the following form:

<form role="search" method="get" id="search-form" name="search-form" action="/video/pesquisa">
                        <div class="cover-pursuit-btn">
                            <button type="submit" value="Search" class="pursuit-btn"><span class="glyphicon glyphicon-search"></span></button>
                        </div>
                        <div class="coversquare">
                            <input type="text" class="square fild-placeholder" placeholder="Find in title or description" id="SearchString" name="SearchString" value="">
                        </div>

</form>

My method in the controller is:

[Route("video/pesquisa/{SearchString}/{page?}")]
public async Task<ActionResult> PesquisaVideo(string SearchString, int? page)
{
...
}

When I do Submit it executes the following URL:

http://localhost:59278/video/pesquisa?SearchString=teste

I do not understand why it does not execute so correct, since I have already applied the route in the annotation:

http://localhost:59278/video/pesquisa/teste

What am I doing wrong?

UPDATING

This is Routeconfig.Cs:

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

            routes.MapMvcAttributeRoutes();

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

        }
  • You have the route Default configured in the RoutesConfig.cs?

  • Yeah, I didn’t change anything on Routesconfig.Cs

1 answer

2


Nothing. It’s all right. That’s because action of form is configured like this:

<form role="search" method="get" id="search-form" name="search-form" action="/video/pesquisa">

Attributes GET do not fit the route formula, however correct the route is. This is due to the fact that an attribute GET is not a route identifier, for example the cliché {controller}/{action}/{id}.

What happens in this cliche case is that the route interpreter analyzes the address and considers part of the route implicitly as an attribute. That is to say, id is not considered a form parameter GET: it becomes a parameter because its route says so.

Now, in your case, you are explicitly using a form and pointing to a action that does not know the route value {SearchString}. In this case is being a bad practice because the form GET asks for free variables, and you are forcing a variable to exist, especially within a route, which is not recognized by the protocol GET (observe what protocol GET is different from the ASP.NET MVC framework).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.