asp.net-mvcmaproute

MVC ASP.NET Map routing is not working with form GET request


In View-

 @using (Html.BeginForm("PageName","ControllerName", FormMethod.Get))
{
  <input type="hidden" name="categoryName" value="Insurance" />                        
  <input type="hidden" id="cityName6" value="Irvine" name="cityName" />
  <input type="hidden" name="page" value="1" />
  <input type="submit" class="btn btn-default" value="Insurance" />
}

In RouteConfig-

routes.MapRoute(
                "SomethingRouteName",
                "{categoryName}/{cityName}/{page}",
                new { controller = "ControllerName", action = "PageName" }
);

I want url to appear like this - Insurance/Irvine/1 But its coming like this- ControllerName/PageName?categoryName=Insurance&cityName=Irvine&page=1

This works fine when I use hyperlink instead of form get method.

@Html.ActionLink("Insurance", "PageName", "ControllerName", new{ categoryName = "Insurance", cityName = "Irvine", page = 1})

//URL shown: Insurance/Irvine/1 as expected. But I have to use form GET method so this hyperlink way is useless.

Please help


Solution

  • You're not passing any route values to Html.BeginForm, so your rendered form element looks like this:

    <form action="/ControllerName/PageName" method="get">
    
    </form>
    

    So when you click submit, it simply appends the values of the form as a query string.

    To fix this:

    @using (Html.BeginForm("PageName", "Home", new {categoryName = "Insurance", cityName = "Irvine", page = "1"}, FormMethod.Get))
    {
        <input type="submit" class="btn btn-default" value="Insurance" />
    }