saidmohamed11
saidmohamed11

Reputation: 275

search method in asp.net mvc

Hello i want to do a search in my database using dropdownlist

this is it :

     @Html.DropDownList("Id", new List<SelectListItem>{
      new SelectListItem {Text="Agent name",Value="1"},
       new SelectListItem {Text="Location",Value= "2",}
         }, "choose",new { @class = "dropdown" })

       <input type="submit" class="submit" value="Search" />

my contoller :

  public ActionResult Index(int Id=1)
    {

        var agentlocation = new AgentLocationViewModel();

            if (Id == 2)
                agentlocation.agents = db.Agents.OrderBy(a =>a 
                   .Location.LocationName).ToList();
            else
            {
                agentlocation.agents = db.Agents.ToList();
            }


        return View(agentlocation);
    }

when the user will choose location the data will be ordered by location

the Problem is when i try to click on search button nothing is happend (it's like the value is null )

Upvotes: 0

Views: 898

Answers (1)

Vano Maisuradze
Vano Maisuradze

Reputation: 5909

You need to add form element. Without form element, nothing will be submited.

<form action="/Home/Index" method="get">
  @Html.DropDownList("Id", new List<SelectListItem>{
  new SelectListItem {Text="Agent name",Value="1"},
   new SelectListItem {Text="Location",Value= "2",}
     }, "choose",new { @class = "dropdown" })

   <input type="submit" class="submit" value="Search" />
</form>

Or using Razor:

@using (Html.BeginForm("Index", "Home", FormMethod.Get))
{
    @Html.DropDownList("Id", new List<SelectListItem>
    {
    new SelectListItem {Text="Agent name",Value="1"},
    new SelectListItem {Text="Location",Value= "2",}
    }, "choose", new { @class = "dropdown" })

    <input type="submit" class="submit" value="Search" />
}

Upvotes: 3

Related Questions