Pankaj Upadhyay
Pankaj Upadhyay

Reputation: 13594

How come the value in search textbox inside a form is saved

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

Upvotes: 0

Views: 1027

Answers (2)

kingdango
kingdango

Reputation: 3999

The answer is Model Binding, a built-in default feature of ASP.NET MVC. With each request to the server the the Model Binder looks for form input values that match properties of objects or parameters of action methods within your controller.

For a more detailed explanation please review: http://dotnetslackers.com/articles/aspnet/Understanding-ASP-NET-MVC-Model-Binding.aspx

Upvotes: 2

Zruty
Zruty

Reputation: 8667

The MSDN article on ModelState is brief, to say the least, but it's ModelState that is responsible for this.

Once @Html.BeginForm() is processed, the controls are populated by the values from ModelState of 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.

Upvotes: 1

Related Questions