简体   繁体   中英

Routing without query string

I have added the following route before the default route

routes.MapRoute(
   name: "RecordDefault",
   url: "{controller}/{action}/{name}",
   defaults: new { controller = "Person", action = "Record" }
);

I can hit the page I want using: sitename/Person/Record/John

But I have an global search in the navigation with the following code

@using (Html.BeginForm("Record", "Person", FormMethod.Get, new { @class = "navbar-form navbar-left" }))
{
       @Html.TextBox("name", "", new { @class = "form-control", placeholder = "Search Name" })
}

When I submit the form the following URL is displayed: sitename/Person/Record?name=John

What do I have to do to ensure the URL is formatted without the query string parameter?

Thanks

Not the same as the posted duplicate, that marked answer does not resolve my problem and according to the comments it also didnt work for others.

Use form post FormMethod.Post instead of Get. So the value will be not appeared in querystring.

@using (Html.BeginForm("Record", "Person", FormMethod.Post, new { @class = "navbar-form navbar-left" }))
{
       @Html.TextBox("name", "", new { @class = "form-control", placeholder = "Search Name" })
}

Your form generates ../Person/Record?name=John because a browser has no knowledge of your routes (which is c# code running on your server). And the HTML standards require that the value of successful form controls be added as query string values when the method is GET.

In order to generate your preferred url ( ../Person/Record/John ), you need javascript to intercept and cancel the default submit, and build a url to navigate to. Using jQuery:

$('form').submit(function() {
    var baseUrl = $(this).attr('action');
    // or var baseUrl = '@Url.Action("Record", "Person")';
    var url = baseUrl + '/' + $('#name').val();
    location.href = url; // redirect
    return false; // cancel the default submit
});

In your Controller add the following -

 [HttpPost]
    public ActionResult Record(string name)
    {
        //code for what needs to be performed.
        return View();
    }

In your view add the following code replacing your existing and check -

@using (Html.BeginForm("Record", "Person", FormMethod.Post))
{
   @Html.TextBox("name")
   <input type="submit" />
}

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