Reputation: 1627
have implemented filtering on my ASP.NET MVC 5 app. My searchbox consists of a few Dropdownlists with predefined values. When the Dropdownlist value changes, the form is submitted and I see all available tickets for a specific method.
After the form submits the page reloads and I see the url like mysite.com/?Method=car
. But I would like to get rid of the query string and put car directly into the url, i.e.
mysite.com/method/car
or mysite.com/method/plain
etc
Is it possible?
Search box
@using (Html.BeginForm("Search", "Transfer", FormMethod.Get))
{
<div class="form-horizontal">
<div class="form-group">
<div class="col-md-10">
@Html.DropDownListFor(model => model.Method, Model.Methods, new { @class = "query"})
</div>
</div>
</div>
<input type="submit" class="hidden" />
}
My action method
[Route("~/transfer/{method?}")]
public async Task<ActionResult> List(string method)
{
//filter and displaying
return View(viewModel);
}
Upvotes: 3
Views: 1753
Reputation: 470
You can call an ajax method on page which will avoid query string and when controller redirects to ActionResult then again you can call ajax method on redirected page. By this way you can avoid query string in MVC. Take below code as example.
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Transfer/search",
data: "{ID:1}",
dataType: "json",
error: function(xhr, ajaxOptions, thrownError) { alert(xhr.responseText); }
});
Make return type as JsonResult of controller method.
Upvotes: 1
Reputation: 8781
By default Html.BeginForm
with FormMethod.Get
will serialize all the form values into query string. So if you want friendly URLs you will have to write some JavaScript (jQuery in this example).
First of all you can remove the form
<div class="form-horizontal">
<div class="form-group">
<div class="col-md-10">
@Html.DropDownListFor(model => model.Method, Model.Methods, new { @class = "query"})
</div>
</div>
</div>
<button type="button" id="submitMethodBtn">Submit</button>
<script>
var baseUrl = '@Url.Action("Search", "Transfer")/'
$('#submitMethodBtn').click(function(){
var url = baseUrl + $(#'@Html.IdFor(m=>m.Method)').val();
window.location.href = url;
})
</script>
Some issues/clarifications:
1if you enter mysite.com/method/car
(assuming that issue #2 is resolved )in browser it will take you to a correct action so your issue is basically generating friendly Url in the view.
2 In the provided code example i used an inline script. You can extract it to a separate static file but you will have to hard-code the url and the html id for Method property.
3 Your action method gets int as parameter so how do you expect it to work with mysite.com/method/car
(car is a string) ?
Upvotes: 3