I am implementing a search filter to one of my application's views. I struggle at getting routeValues passed to controller action using @Html.BeginForm() and GET request.
The action accepts the following properties:
public ActionResult Books(int id, string type, string search)
{
//rest of the code
}
The View's search box looks like this:
@model ILookup<string, CityLibrary.Models.Library.Book>
....
@using (Html.BeginForm("Books", "Collections", new { id = Model.First().First().CollectionId, type = ViewBag.BookType }, FormMethod.Get, null))
{
<div class="input-group col-md-4">
@Html.TextBox("search", null, new { @class = "form-control form-control-fixed-width", @placeholder = "Filter title..." })
<span class="input-group-btn">
<button class="btn btn-default" type="submit">
<span class="glyphicon glyphicon-search"></span>
</button>
</span>
</div>
}
The problem occurs when I am submitting the search box. The controller action gets the id and search string, but type is always null, even though ViewBag.BookType is not null. Fiddler shows this:
GET /Collections/Books/2?search=searchterm
Which seems to be completely ignoring type parameter in the request.
Source code in browser:
<form action="/Collections/Books/2?type=available" method="get">
<div class="input-group col-md-4">
<input class="form-control form-control-fixed-width" id="search" name="search" placeholder="Filter title..." type="text" value="" />
<span class="input-group-btn">
<button class="btn btn-default" type="submit">
<span class="glyphicon glyphicon-search"></span>
</button>
</span>
</div>
</form>
Does it have something to do with GET method? I would like to avoid POSTing as I would have to write another controller action with basically the same code.
EDIT: It seems that the problem occurs when I try to use GET request. POSTing the form actually passes all the parameters to the controller action. Why is that?
ViewBag.BookTypeisnull. Add a<div>@ViewBag.BookType</div>in your view and confirm it.@ViewBag.BookTypeis also used in the View at the top (a simpleif/elsestatement to display a correct header). I also tried to hardcode the type property.@using (Html.BeginForm("Books", "Collections", new { id = Model.First().First().CollectionId, type = "available" }, FormMethod.Get, null))also returnstypeofnull...../{id}/{type}(if not then a route value cannot be added)/Collections/Books/2?type=available&search=searchterm.type. And if you have the default route, then you do not even need thenew { id = Model.First().First().CollectionId }code