3

It's been days since I started to study MVC programming and honestly I'm still coping up to new environment of MVC.

In my project, I started to create a data table that display the data in my database using these codes.

This is my codes in view and controller. This part runs very well.

 <table id="table1" >
<thead>
    <tr>
        <th>id</th>
        <th>title </th>
        <th>
            description
        </th>

    </tr>
</thead>
<tbody>
    @foreach (var item in Model)
    {

        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.id)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.title)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.description)
            </td>

        </tr>
    }
    </tbody>
  </table>
     }

   var charts = (from p in db.pmTA_ProjectCategory

                      select new
                      {
                          id = p.id,
                          title = p.title,
                          description = p.description,

                      }).ToList()
                 .Select(x => new pmTA_ProjectCategory()
                 {
                     id = x.id,
                     title = x.title,
                     description = x.description,

                 });

        return View(charts.ToList());

But I noticed that I need to filter my data using dropdown so I added drop down to my View again.

This is my code in view and controller to display the dropdown and data inside the dropdown.

 <div>
 @Html.DropDownList("projectcat", ViewBag.proj as SelectList, "Select...", new { 
 @class = "form-control" })
 </div>

         var data1 = from p in db.pmTA_ProjectCategory
                    select new
                    {
                        id = p.id,
                        title = p.title,
                        description = p.description
                    };

         SelectList list = new SelectList(data1, "id", "title");
         ViewBag.proj = list;

when it comes to displaying the data inside the dropdown it runs again smoothly.

My problem is, I need to filter the data of data table using dropdown automatically. I mean, when I selected the value of dropdown the data table must show the data corresponds to the selected value in dropdown

I created codes in javascript to filter the data of datatable using dropdown.

This is the code:

 <script>
    $(document).ready(function () {
        var table = $("#table1").DataTable();

        $("#projectcat").change(function () {
            table.search(this.value).draw();
        });

    });
   </script>

But the data in my data table is not responding and not functioning, when I selected the data in dropdown the datatable can't filter.

1
  • it not working for me but thanks a lot for your help I really appreciate it
    – Eemq07
    Aug 31, 2018 at 7:50

2 Answers 2

3

1) Your view should be of strongly type of IEnumerable<ProjectCategory>

2) Add drop down to your view

<div class="dropdown">
    @Html.DropDownList("id", (List<SelectListItem>)ViewBag.proj, "--Select id--", new { @onchange = "CallChangefunc(this.value)" })
</div>

3) Add partial view of IEnumerable<ProjectCategory> in your view. When you adding partial view then check it as Create as a partial view.

The name of your partial view is _GetItem.cshtml

The content of partial view

<table id="table1" >
<thead>
    <tr>
        <th>id</th>
        <th>title </th>
        <th>
            description
        </th>

    </tr>
</thead>
<tbody>
    @foreach (var item in Model)
    {

        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.id)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.title)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.description)
            </td>

        </tr>
    }
    </tbody>
  </table>

And call this partial view in your view just below to your drop down that you added earlier.

<div id="myPartialView">
    @{Html.RenderPartial("_GetItem", Model);}
</div>

4) You action method in controller would be

public ActionResult Index()
{
    var charts = db.ProjectCategories.ToList();

    List<SelectListItem> dropDownItems = charts.Select(c => new SelectListItem { Text = c.title, Value = c.id.ToString() }).ToList();
    ViewBag.proj = dropDownItems;

    return View(charts);
}

5) Add ajax call to your view that called when you change any option in your drop down

<script>

    function CallChangefunc(id) {
         $.ajax({
             url: "@Url.Action("GetItem", "Default")",
             data: { id: id },
            type: "Get",
            dataType: "html",    
             success: function (data) {
                 console.log(data);
                //Whatever result you have got from your controller with html partial view replace with a specific html.
                $("#myPartialView").html( data ); // HTML DOM replace
            }
        });
    }

</script>

6) And finally your ajax call hit below action method that can render only partial view

public PartialViewResult GetItem(int id)
{
    var charts = db.ProjectCategories.ToList();
    var model = charts.Where(x => x.id == id).ToList();
    return PartialView("_GetItem", model);
}
10
  • @Eemq07, view the answer might be it help you :)
    – er-sho
    Aug 31, 2018 at 9:28
  • thank you for your codes it really helps me a lot... thank again... can I ask you another question? what if I added another two drop down? does your javascript must be edited again ? can you help about that matter? Im still new in creating script ... thank again
    – Eemq07
    Aug 31, 2018 at 13:27
  • @Eemq07, If answer help you then please accept it and vote up
    – er-sho
    Aug 31, 2018 at 13:30
  • And one more question... about the data table ... is it possible that the data of datatable will show only once I selected the value of dropdown ?
    – Eemq07
    Aug 31, 2018 at 13:31
  • @Eemq07, kingly post a new question for your problem so that this question's integrity will be maintain and give me url for such question then I'll definitely help you
    – er-sho
    Aug 31, 2018 at 13:31
0

Current status :

  • You have created a drop down list id='projectcat'
  • Datatable $("#table1") is not responding on change event

Solution :

  • Your code looks correct there is nothing wrong with it.
  • Running same kind of example below is working correctly
  • Make sure there is no other javascript error blocking this code
  • Apply debugger inside $("#projectcat").change(function () { debugger; }); to debug code in developer toolbar

Check below example, changing drop down value its also filtering datatable:

$(document).ready(function () {
    var table = $("#table1").DataTable();

    $("#projectcat").change(function () {
        console.log('Groing for folter : ' + this.value);
        table.search(this.value).draw();
    });

});
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" />


<p>Change datatable filter value : </p>
<select id="projectcat">
    <option>Rhona</option>
    <option>Colleen</option>
    <option>Jena</option>
    <option>Tiger</option>
</select>

<hr />
<table id="table1" class="display" style="width:100%">
    <thead>
        <tr>
            <th>Name</th>
            <th>Salary</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Tiger Nixon</td>
            <td>$320,800</td>
        </tr>
        <tr>
            <td>Rhona Davidson</td>
            <td>$327,900</td>
        </tr>
        <tr>
            <td>Colleen Hurst</td>
            <td>$205,500</td>
        </tr>
        <tr>
            <td>Sonya Frost</td>
            <td>$103,600</td>
        </tr>
        <tr>
            <td>Tiger Kennedy</td>
            <td>$313,500</td>
        </tr>
        <tr>
            <td>Rhona Kennedy</td>
            <td>$12,900</td>
        </tr>
    </tbody>
</table>

7
  • mine is not functioning ... is there any option I can used in order to filter my datatable using dropdown without using plugin of .datatable() ?
    – Eemq07
    Aug 31, 2018 at 6:42
  • @Eemq07, Make sure there is no any other javascript error in document. Press F12 and find Console panel for Firefox, run your webpage and check for any other error.
    – saAction
    Aug 31, 2018 at 6:46
  • I still can't find it because I think the problem is really my javascript , I cant find any replacement for that code
    – Eemq07
    Aug 31, 2018 at 7:49
  • I created another script but still it's not working <script>$("#funds").change( function (event) { var userId = $(this).val(); $.ajax({ url: "@Url.Action("GetUser","Sample2")", data: { id : userId }, type: "Get", dataType: "html", success: function (data) { //Whatever result you have got from your controller with html partial view replace with a specific html. $("#divPartialView").html(data); // HTML DOM replace } }); }); </script>
    – Eemq07
    Aug 31, 2018 at 8:25
  • this is from the link I saw
    – Eemq07
    Aug 31, 2018 at 8:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.