Hicham4
Hicham4

Reputation: 39

How can I filter a list with a dropdown list

I am new to MVC, and I want on my view two things:

1 - A list of data's (3 columns) 2 - A dropdown list that I can filter the list (filled with data from the first column)

in my controller I have the following function:

public ViewResult ListUrl()
{
    var ws = new Service1();
    localhost.Service1 s1 = new Service1(); // data from web services
    localhost.UrlInfo[] ui = s1.GetUrlInfo();
    for (int i = 0; i < ui.Length; i++)
        {
            var UrlItem = new UrlItem();
            UrlItem.Id = Convert.ToInt32(ui[i].Id);
            UrlItem.urlll = ui[i].url;
            UrlItem.toontijd = ui[i].ToonTijd;
            UrlItem.positie  = Convert.ToInt32(ui[i].positie);

            Models.ListUrl.UrlList.Add(UrlItem);
        }

        var urlname = from url in s1.GetUrlInfo() select url  ;
        ViewData["url"] = new SelectList(urlname, "Id", "url");

    return View();

}

In the view :

<script type="text/javascript">
$(document).ready(function () {

   // How can I filter the list (see <table> tag) when I change index of dropdown list???

});
</script>

@Html.DropDownList("SelectedItem", (SelectList)ViewData["url"], "----- all ------", new { id = "0", text = "----- all ------" })

<table>
<tr>
    <th>
        Url
    </th>
    <th>
        Toontijd
    </th>
    <th>
        Positie
    </th>
</tr>

@foreach (var item in ListUrl.UrlList)
{
    <tr>
        <td>
            @item.urlll.ToString()        
        </td>
        <td>
            @item.toontijd.ToString()

        </td>
        <td>

        </td>
        <td>
            @item.positie.ToString()
        </td>
    </tr>

}

How to get dropdownlist change event working? Thanks a lot.

Hicham.

Upvotes: 0

Views: 3061

Answers (1)

Paritosh
Paritosh

Reputation: 11598

Well.. You need to do some stuff for this.. Let me explain in steps..

  1. Create a partial view for the grid
  2. Attach onchange event for dropdown
  3. Make one controller action method which take dropdown selection as parameter and returns the grid partial view as result

    $.get('yourActionURL', { parameter: $('#yourDropdownId').val() }, function(result) {
        $('#grid').html(result);
    });
    

Filtering a WebGrid with a DropDownList in MVC4 and ASP.NET MVC Filtering results in a list/grid - these link can help you in details about this.

Upvotes: 1

Related Questions