9

I am new to Asp.net MVC and have no idea as to how can i perform the search. Here's my requirement, please tell me how will you handle this :-

I need to have textbox where user can enter a search query or string. The user then clicks on a button or presses enter to submit it. The string needs to matched with a table's property name.

NOTE:- Querying the data and fetching the result isn't the main point here. All I need to know is how will you take the user input and pass it to a controller action or whatever for further processing. Just tell me how will you read the user input and where will you send it to search.

MoXplod
  • 3,813
  • 6
  • 36
  • 46
Pankaj Upadhyay
  • 12,966
  • 24
  • 73
  • 104

3 Answers3

11

Asp.Net MVC uses standard HTTP verbs. For the html part, it's a normal html form that points to an url. Server side, that url will be routed to a controller/action which will handle the input and do what is needed.

Let's have a sample. You want to make a search form. First of all, it's a best practice to have search forms use the HTTP GET method instead of POST, so the search results can be bookmarked, linked, indexed, etc. I won't be using Html.BeginForm helper method to make things more clear.

<form method="get" action="@Url.Action("MyAction", "MyController")">
<label for="search">Search</label>
<input type="text" name="search" id="search" />
<button type="submit">Perform search</button>
</form>

That's all the html you need. Now you'll have a controller called "MyController" and the method will be something like this:

[HttpGet]
public ActionResult MyAction(string search)
{
//do whatever you need with the parameter, 
//like using it as parameter in Linq to Entities or Linq to Sql, etc. 
//Suppose your search result will be put in variable "result".
ViewData.Model = result;
return View();
}

Now the view called "MyAction" will be rendered, and the Model of that view will be your "result". Then you'll display it as you wish.

Matteo Mosca
  • 7,380
  • 4
  • 44
  • 80
8

As always in an ASP.NET MVC application you start by defining a view model which will express the structure and requirements of your view. So far you have talked about a form containing a search input:

public class SearchViewModel
{
    [DisplayName("search query *")]
    [Required]
    public string Query { get; set; }
}

then you write a controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new SearchViewModel());
    }

    [HttpPost]
    public ActionResult Index(SearchViewModel model)
    {
        if (!ModelState.IsValid)
        {
            // There was a validation error => redisplay the view so 
            // that the user can fix it
            return View(model);
        }

        // At this stage we know that the model is valid. The model.Query
        // property will contain whatever value the user entered in the input
        // So here you could search your datastore and return the results

        // You haven't explained under what form you need the results so 
        // depending on that you could add other property to the view model
        // which will store those results and populate it here

        return View(model);
    }
}

and finally a view:

@model SearchViewModel

@using (Html.BeginForm())
{
    @Html.LabelFor(x => x.Query)
    @Html.EditorFor(x => x.Query)
    @Html.ValidationMessageFor(x => x.Query)
    <button type="submit">Search</button>
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • First of all thanks mate. As you can see, in other answer @Matteo Mosca has mentioned the use of HTTP verbs. Do you think one should use that or always follow the viewmodel usage for such purposes – Pankaj Upadhyay Nov 17 '11 at 13:50
  • 1
    @Pankaj Upadhyay, view models and HTTP verbs are two completely different notions that have nothing in common. You should always use view models in an ASP.NET MVC application and as far as HTTP verbs are concerned, well, since it is a web application and is based on the HTTP protocol you are already using HTTP verbs. You could use GET verb on the HTML form as well if you want. The Html.BeginForm helper has an overload which allows you to specify this: `@using (Html.BeginForm(null, null, FormMethod.Get)) { ... }`. Then remove the `[HttpPost]` attribute from the action you are submitting to. – Darin Dimitrov Nov 17 '11 at 13:51
  • ya...dats what i was saying the use of GET verb. Don't you think for such purposes, it would be better to use this rather than viewmodel ? Because this way one doesn't need to create a separate viewmodel for just taking the input query. – Pankaj Upadhyay Nov 17 '11 at 14:03
  • 3
    @Pankaj Upadhyay, you could still use the view model with GET verb on the form. I think that you should always use view models. – Darin Dimitrov Nov 17 '11 at 14:04
3

This is the best way to do it.

Create a ViewModel

public class SearchViewModel
{
    public string Query { get; set; }
}

Create a Controller

    public class SearchController : Controller
    {
        [HttpPost]
        public ActionResult Search(SearchViewModel model)
        {
            // perform search based on model.Query

            // return a View with your Data.
        }
    }

Create the View

// in your view
@using (Html.BeginForm("Search", "SearchController"))
{
    @Html.TextBox("Query")
    <input type="submit" value="search" />
}

hope this helps

dknaack
  • 60,192
  • 27
  • 155
  • 202