How to define Html.BeginForm for attribute routing actions?

controller

[HttpGet]
[Route("~/search/{clause}/{skip?}")]
public async Task<ActionResult> Search(string clause, int skip = 0)
{
   ...
}

      

View

@using (Html.BeginForm("Index", "search", FormMethod.Get))
{
    @Html.TextBox("clause", null, new { @class = "form-control col-md-4" })
    ...
}

      

Rendered Html

<form action="/search" method="get">
    <input id="clause" name="clause" type="text" value="test">
</form>

      

I use this [HttpGet]

partly because I want the search to go throughhttp://myapp.com/search/<search values>

When I go to http://myapp.com/search/test

everything seems fine, but when I try to type my new search term in the textbox and press enter or submit it goes tohttp://myapp.com/search?clause=newsearch

What should I do to get the textbox to move to instead http://myapp.com/search/newsearch

?

+3


source to share


1 answer


Your form is generating http://myapp.com/search?clause=newsearch

because the browser doesn't know your routes (C # code running on your server).

In order to create the preferred url ( http://myapp.com/search/newsearch

) you need javascript to intercept and cancel the default submit and create a referral url. Using jQuery:



$('form').submit(function() {
    var baseUrl = $(this).attr('action'); // or var baseUrl = '@Url.Action("Index", "search")';
    var url = baseUrl + '/' + $('clause').val(); // add value for skip if required
    location.href = url; // redirect
    return false; // cancel the default submit
});

      

0


source







All Articles