I am trying to implement search functionality in Asp.net MVC Razor. What i am finding strange is the retrieval of value in search texbox (though i want this, but will like to know whats happening under the hood).
Following is the HTML code :-
@using (Html.BeginForm("Search", "Home", FormMethod.Get))
{
@Html.TextBox("query")
<input type="submit" value="Submit" />
}
Here is the controller code :-
public ActionResult Search(string query, int? page)
{
int pageIndex = page ?? 1;
ViewBag.query = query;
PagedList.IPagedList<Product> PagedProducts = dbStore.Products.Where(p => p.Name.Contains(query)).ToList().ToPagedList(pageIndex, PageSize);
return View(PagedProducts);
}
NOTE:- The above HTML code resides on a shared _Layout.cshtml i.e. masterpage file
The MSDN article on ModelState is brief, to say the least, but it’s
ModelStatethat is responsible for this.Once
@Html.BeginForm()is processed, the controls are populated by the values fromModelStateof the current model, if it’s applicable.You can override this behavior (and force clear the textboxes) by calling
ModelState.Clear()in your action method.